May 18, 2011

Get size (width, height) of a View

This example show how to read size of a view (Button in this example), using getWidth(), getHeight().

Get size (width, height) of a View

Be aware not to call getWidth() or getHeight() too early before the view have been laid out on the screen, otherwise "0" will be returned.

package com.AndroidResizeView;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidResizeView extends Activity{

TextView textMyTextView, textViewWidth, textViewHeight;
Button myButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textMyTextView = (TextView)findViewById(R.id.mytextview);
textViewWidth = (TextView)findViewById(R.id.viewwidth);
textViewHeight = (TextView)findViewById(R.id.viewheight);
myButton = (Button)findViewById(R.id.mybutton);

myButton.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
updateSizeInfo();
}});
}


@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
updateSizeInfo();
}


private void updateSizeInfo(){

textViewWidth.setText(String.valueOf("Button's Width(pixels): " + myButton.getWidth()));
textViewHeight.setText(String.valueOf("Button's Height(pixels): " + myButton.getHeight()));
}

}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/mytextview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/mybutton"
android:layout_width="200px"
android:layout_height="wrap_content"
android:text="Check my size"
/>
<TextView
android:id="@+id/viewwidth"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/viewheight"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


next:
- Resize Button programmatically using Java Code

2 comments:

  1. thank you for this code, it works for me!
    now my problem is that I have an ImageView in my layout and I want to get its width and height without having to do anything (no click on button ...).
    Do you have any idea how to do that??

    ReplyDelete

Infolinks In Text Ads