1

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!

wmcnally
  • 147
  • 2
  • 14
  • Regarding to the android documentation ` android:visibility:gone` set the view to doesn't take any layout space. Just a suggestion:try using invisible instead of gone. – Mike Nov 22 '14 at 23:05
  • Please give feedback if it works – Mike Nov 22 '14 at 23:07
  • invisible and visible both did not work. – wmcnally Nov 22 '14 at 23:11
  • You ImageView matches the width of parent. Why you don't get the width of the parent as it is the same of the child imageview. You are providing not much information so it's difficult to help xou – Mike Nov 22 '14 at 23:15
  • ah ok good point I'll try that – wmcnally Nov 22 '14 at 23:15
  • Maybe you're trying to use the width before it was set? Try to put your Toast in OnLayoutChangeListener http://developer.android.com/reference/android/view/View.html#addOnLayoutChangeListener(android.view.View.OnLayoutChangeListener) – Zielony Nov 23 '14 at 00:19

1 Answers1

1

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)
        }
});
romtsn
  • 11,704
  • 2
  • 31
  • 49