简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM