saeid ezzati
saeid ezzati

Reputation: 891

How to detect the height of a view?

I have 2 layouts:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/addhere"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </RelativeLayout>

</ScrollView>

a.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_height="200dp"
        android:layout_width="match_parent"/>

</LinearLayout>

and I want to inflate a.xml layout and add it to the view group with id addhere and then detect the height of a's view. a.getHeight() gives me 0.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        View a = getLayoutInflater().inflate(R.layout.a,null);
        ViewGroup b = (ViewGroup)findViewById(R.id.addhere);
        b.addView(a);
        Log.d("states", a.getHeight() + ""); // show me 0

    }

Please tell me how I can detect the height of a's view?

Upvotes: 1

Views: 630

Answers (3)

Neil
Neil

Reputation: 664

This is because the view tree is still not measured and laid out at the time onCreate() is called.
If api < 11 use view.getViewTreeObserver().addOnGlobalLayoutListener()
else use view.addOnLayoutChangeListener().
Remember to remove listener in both cases.

Upvotes: 2

Vitaly Zinchenko
Vitaly Zinchenko

Reputation: 4911

a.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        Log.d("states", "a's height: " + v.getHeight());
        a.removeOnLayoutChangeListener(this);
    }
});

Upvotes: 2

Marius Constantin
Marius Constantin

Reputation: 178

You can try something like this:

final View view=a;
    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
    {
        @TargetApi(16)
        @Override
        public void onGlobalLayout()
        {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
            {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            else
            {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }

            final int width=view.getWidth();
            final int height=view.getHeight();
        }
    });

Upvotes: 1

Related Questions