Device Height And Width Via GlobalLayoutListner

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. This example shows how to register global layout listener.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it GlobalLayoutListner.

2.) Write following into main.xml:

 

<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>

 

 

3.) Run for output.

Steps:

1.) Create a project named GlobalLayoutListner and set the information as stated in the image.

Build Target: Android 4.4
Application Name: GlobalLayoutListner
Package Name: com.example.GlobalLayoutListner
Activity Name: GlobalLayoutListnerActivity

globallayoutlistner1

2.) Open GlobalLayoutListnerActivity.java file and write following code there:

 

package com.example.globallayoutlistner;

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

public class GlobalLayoutListnerActivity extends Activity {

LinearLayout mainLayout;
TextView displayBefore, displayAfter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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()));

}

};
}

 

 

3.) Compile and build the project.

Output

globallayoutlistner2