wrap_content not working [closed]

0

I have an error with wrap_content on android in my ImageButton I set the image directly from a URL

EXAMPLE:

ImageButton img = (ImageButton) findViewById(R.id.imageButton);
Picasso.with(getContext()).load("https://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png").fit().into(img);

and the XML of this ImageButton is as follows

<ImageButton
                android:id="@+id/imageButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitEnd" />   

Image display I receive

    
asked by anonymous 24.07.2017 / 14:27

1 answer

1

The wrap_content in ImageViews only works if the image is already of known size, since the layout is inflated as soon as the Activity begins. And in your case your image will still be uploaded from the web.

My suggestion, since you are using Picasso, is to load the image as a Bitmap to a Target and use the onBitmapLoaded() callback method to determine that the image is ready, so you still in that method you can access the width and height properties of the image and resize the ImageView according to SetLayoutParams() .

Something like this:

        Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                if (bitmap != null) {
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    // OBS: Crie um LayoutParams de acordo com o ViewGroup pai da ImageView. 
                    // No meu exemplo, estou supondo que a ImageView está dentro de um 
                    // FrameLayout.
                    imageView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
                    imageview.setImageBitmap(bitmap);
                }
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {}

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {}
        };

        Picasso.with(this)
                .load(url)
                .into(target);
    
24.07.2017 / 16:15