Sunday, July 3, 2011

Get width and height of ImageView

To get width and height of ImageView, we can call getWidth() and getHeight(). But it's invalid before the ImageView have been actually drawn.

Get width and height of ImageView

When getWidth() and getHeight() are called in onCreate(), before actually drawn; "0" will be return.

package com.exercise.AndroidImageViewSize;

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

public class AndroidImageViewSizeActivity extends Activity {

ImageView image;
TextView info1, info2;
Button buttonCheckNow;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

image = (ImageView)findViewById(R.id.image);
info1 = (TextView)findViewById(R.id.info1);
info2 = (TextView)findViewById(R.id.info2);

info1.setText("image size@onCreate() - " + String.valueOf(image.getWidth())
+ " : " + String.valueOf(image.getHeight()));

buttonCheckNow = (Button)findViewById(R.id.checksize);
buttonCheckNow.setOnClickListener(new Button.OnClickListener(){

public void onClick(View arg0) {
// TODO Auto-generated method stub
info2.setText("image size NOW - " + String.valueOf(image.getWidth())
+ " : " + String.valueOf(image.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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/icon"
/>
<Button
android:id="@+id/checksize"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Check ImageView size now"
/>
<TextView
android:id="@+id/info1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/info2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


No comments: