pblead26
pblead26

Reputation: 810

Set Height of View as Percentage of screen size(Programmatically)

I am using AndroidSlidingUpPanel library. https://github.com/umano/AndroidSlidingUpPanel

My activity_main.xml has two children. The first child is the main layout. The second child is the layout for the sliding up panel. here I have posted the layout of the Sliding Up Panel. There are 4 LinearLayouts defined in the ratio percentage of 15 : 15 : 60 : 10 %. The first layout will be visible in the panel. Now I want the panel height to be 3/4th of the first layout. So here, the first layout is taking 15% of the screen but the panel height should be around 10-12 % of the screen.

Is there any way or formula that I can use to get the screen size and that sets the panel Height according the 1st layout of the xml file provided here.

I have tried to define the panel height in the Java code. but no success till now. Sometimes the 2nd layout is also shown in the panel, sometimes only half or 1/4th of the 1st layout.

PS : Is there any way to find a height of a view BEFORE setContentView()?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_weight="1.5"
    android:background="#666666" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:layout_weight="1.5"
    android:background="#888888" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="6"
    android:background="#eeeeee" >
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#202033" >
</LinearLayout>

Upvotes: 2

Views: 2771

Answers (1)

harveyslash
harveyslash

Reputation: 6014

It is possible to get the height of the Screen in Pixels. It is also possible to get the density of the screen(DPI). The ratio of the two will give you the physical height of the screen.

 DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();

      float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
      float dpWidth = displayMetrics.widthPixels / displayMetrics.density;

After getting the dpWidth (which is a physical quantity independent of density), you can easily apply percentages to it.

Upvotes: 8

Related Questions