Monday, January 30, 2017

Get height of the view

Method getHeight() will always return 0 cause you are trying to get the size before the view is drawn, another possible solution could be to do a Post with a runnable on the View.

1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#e6e6e6"
    android:orientation="vertical" >
        <ImageView
            android:id="@+id/image"
            android:layout_gravity="center"
            android:layout_height="300dp"
            android:layout_width="300dp"
            android:src="@mipmap/ic_launcher"/>
</LinearLayout>

2.MainActivity.java

    final ImageView imageView = (ImageView) findViewById(R.id.image);
        Log.d("TEST", "" + imageView.getHeight());
        //Will return height = 0;

        imageView.post(new Runnable(){
            public void run(){
                Log.d("TEST", "" + imageView.getHeight());
                //Will return specific height
            }
        });


EmoticonEmoticon