and
and

Reputation: 351

Why I get the 0 value when using the imageView.getWidth()

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());
    }}

Upvotes: 1

Views: 703

Answers (3)

Mike76
Mike76

Reputation: 979

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

Upvotes: 0

Mike
Mike

Reputation: 4570

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?

Upvotes: 5

Danail Alexiev
Danail Alexiev

Reputation: 7772

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().

Upvotes: -1

Related Questions