Question

this is my first post. I am learning to code in java for android apps. I am using a LinearLayout "variable named: ll" with a predefined layout_weight (which I want to change whenever I want in the future) and height and width set to MATCH_PARENT. I want to get the height of this LinearLayout in pixels. I fill this using java (ll.addView(variableForAnObject);). I am trying to get its height using ll.getLayoutParams().height; but I am getting -1. Because I believe this is the constant for MATCH_PARENT. Setting the height to 0dp makes the ll invisible and gives height as 0.

Please tell me if there's a way to get its height. I think I can do this by getting screen height using DisplayMetrics and making nearly impossible calculations (for me, at least) but this will be too complex.

Was it helpful?

Solution

try with ll.getHeight() should work

if not, it's because android has not yet calculed its bounds, then:

//inside of onCreate method should work
ll.post(new Runnable() {
    @Override
    public void run() {
        //maybe also works height = ll.getLayoutParams().height;

        height  = ll.getHeight();

    }
});

OTHER TIPS

It is -1 because its dimensions have not yet been set, whenever you set layout it takes some time to compute the actual values including height, width etc.

Use OnLayoutListener to listen when it has finished with the layout.

layout.onLayoutChange (View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
    //Extract values here
    height = view.getHeight();
    width = view.getWidth()
}

See this for more about the OnLayoutListener

Define your LinearLayout in your class and use getHeight() and getWidth(). Example:

LinearLayout yourLayout = (LinearLayout) findViewById (R.id.yourLL);
double height = yourLayout.getHeight();
double width = yourLayout.getWidth();

Hope it helps! :)

Give the id field in your layout xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:id="@+id/<ID>>

Use this id to get reference in java class and find height and width:

LinearLayout linearLayout= (LinearLayout) findViewById (R.id.<ID>);
double height = linearLayout.getHeight();
double width = linearLayout.getWidth();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top