wmcnally
wmcnally

Reputation: 147

Get ImageView width in getView

I can't get the width of an ImageView in my ListAdapter's getView method...

<ImageView
        android:id="@+id/photoPost"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:visibility="gone" />

In my ListAdapter's getView...

holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost);
int targetHeight = holder.photoPost.getWidth() * (9/16);

I'm toasting the targetHeight and it's always 0 which means the getWidth() method is returning 0. I've tried many different things. Please help!

Upvotes: 1

Views: 1003

Answers (1)

romtsn
romtsn

Reputation: 11992

The problem is that when you try to getWidth, your ImageView have not been appeared on the screen, so it always returns 0. So there are two ways, you can get the width:

First way

You need to measure your ImageView and then get the measuredWidth:

holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost);
holder.photoPost.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

int targetHeight = holder.photoPost.getMeasuredWidth() * (9/16);

Second way

Add onGlobalLayoutListener to your ImageView and then, you will be able to get the width:

holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost);
holder.photoPost.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                holder.photoPost.getViewTreeObserver()
                        .removeOnGlobalLayoutListener(this);
            } else {
                holder.photoPost.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
            }

            int targetHeight = holder.photoPost.getWidth() * (9/16)
        }
});

Upvotes: 1

Related Questions