سؤال

That's my source code to create a new ImageView:

    ImageView image = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.width = screen_dimens(0.5, "w");
            params.height = screen_dimens(0.5, "w");
            image.setLayoutParams(params);

(screen_dimens(0.5, "w")=50% of screen width)

But now when I want to get the width of the Image, I get the following results:
image.getWidth() => 0
image.getLayoutParams().width => 360

Now what is the difference between those two functions? And how can I set the Image-width so the getWidth() method also returns the correct value?

هل كانت مفيدة؟

المحلول 2

Use this to set width and height :

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);

نصائح أخرى

Even you have set width and height for a ImageView or any View by using LayoutParams, imageView.getWidth() always returns 0 until it is drawn in its parent.

u can use

    image.post(new Runnable() {
        public void run() {
            image.getMeasuredHeight();
        }
    });

instead of

   image.getWidth()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top