romanPotapskyi
romanPotapskyi

Reputation: 37

imageView return getWidth zero

My imageView in xml:

<ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/ivManagePhoto"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp" />

My code:

    ImageView ivManagePhoto;
    ivManagePhoto = (ImageView)findViewById(R.id.ivManagePhoto);
   double ivw = ivManagePhoto.getWidth();

When i try to get ivManagePhoto.getWidth(); that return 0, but i need to get mathparent size.

Upvotes: 0

Views: 666

Answers (2)

juankirr
juankirr

Reputation: 323

You can wait to onwindowfocuschanged event. At this time UI items are already loaded

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        //get sizes you want
        Point screen_size=new Point();
        getWindowManager().getDefaultDisplay().getSize(screen_size);
        int width = screen_size.x;
        int height = screen_size.y;
        //...
    }
    //...
}

Upvotes: 0

Volodymyr Yatsykiv
Volodymyr Yatsykiv

Reputation: 3211

You can try this:

imageView.post(new Runnable() {
            @Override
            public void run() {
                imageView.getWidth();
            }
        });

or, try this:

ViewTreeObserver viewTreeObserver = rootLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
  viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
      rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
      viewWidth = view.getWidth();
    }
  });
}

Hope this code will help you.

Upvotes: 2

Related Questions