Get width and height of View in OnGlobalLayoutListener()

As you know, to get dimension of any View, you can call its getWidth() and getHeight() methoda. But it's not valid when its has not been laid out yet, such as in onCreate(). In order to read dimension when the layout ready, you can implement your OnGlobalLayoutListener, and register it by calling View.getViewTreeObserver().addOnGlobalLayoutListener().

Example:

Get width and height of View in OnGlobalLayoutListener()
Get width and height of View in OnGlobalLayoutListener()


package com.example.androidongloballayoutlistener;

import android.os.Bundle;
import android.app.Activity;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

LinearLayout mainLayout;
TextView displayBefore, displayAfter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mainLayout = (LinearLayout)findViewById(R.id.mainlayout);
displayBefore = (TextView)findViewById(R.id.displaybefore);
displayAfter = (TextView)findViewById(R.id.displayafter);

displayBefore.setText(String.valueOf(mainLayout.getWidth()) +
" : " + String.valueOf(mainLayout.getHeight()));

mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(myOnGlobalLayoutListener);
}

OnGlobalLayoutListener myOnGlobalLayoutListener =
new OnGlobalLayoutListener(){

@Override
public void onGlobalLayout() {
displayAfter.setText(String.valueOf(mainLayout.getWidth()) +
" : " + String.valueOf(mainLayout.getHeight()));

}

};
}


<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity"
android:id="@+id/mainlayout">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View size onCreate()" />
<TextView
android:id="@+id/displaybefore"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View size at OnGlobalLayoutListener()" />
<TextView
android:id="@+id/displayafter"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


0 Response to "Get width and height of View in OnGlobalLayoutListener()"

Posting Komentar