1

I want get the width value from the imageView object but when I run the following code It returns a 0 value. Why I get the 0 value when using the imageView.getWidth()? How can I solve this problem?

public class MainActivity extends Activity {
ImageView imageView;
TextView textView;


 protected void onCreate(Bundle bundle) {
 super.onCreate(bundle);
 setContentView(R.layout.activity_main);
 imageView= (ImageView) findViewById(R.id.imageView);
 textView = (TextView) findViewById(R.id.textView);
 Integer i = imageView.getWidth();
 textView.setText(i.toString());
    }}
and
  • 341
  • 1
  • 3
  • 11
  • That's because the layout traversal hasn't happened at that stage yet, how to fix that really depends on why you want to know, i.e. what you want to do with it. – ci_ Sep 07 '15 at 20:39
  • 1
    See here http://stackoverflow.com/questions/10411975/how-to-get-the-width-and-height-of-an-image-view-in-android And here http://stackoverflow.com/questions/18268915/views-getwidth-and-getheight-returning-0 – Salauddin Gazi Sep 07 '15 at 20:43

3 Answers3

5

Simply read the width of the ImageView in it's post method like this:

public class MainActivity extends Activity {
    ImageView imageView;
    TextView textView;

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        textView = (TextView) findViewById(R.id.textView);
        imageView.post(new Runnable() {
            @Override
            public void run() {
                Integer i = imageView.getWidth();
                textView.setText(i.toString());
            }
        });
    }
}

The post callback is executed once all the ImageView's lifecycle methods are called, which means the whole view is already measured, therefore you have a proper width of the view.

Does this help?

Mike
  • 4,550
  • 4
  • 33
  • 47
0

You can either move the call to view.post() or to activity.onPostResume(). At this stage the view should be fully initialized.

Mike76
  • 899
  • 1
  • 9
  • 31
-1

It's very possible than on create the view hierarchy isn't inflated yet, so the view's dimension have not yet been set. I would move this call to a later stage of the activity lifecycle, maybe to onResume().

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28