Search code examples
androidandroid-glide

Glide-loaded Drawable cannot be set as background for Button, works for ImageButton


I am unable to load a Drawable from a bitmap, into a Button instance:

        Glide.with(hostFragment.getActivity())
                .load(internetHttpUrl)
                .apply(new RequestOptions()
                        .override(150, 150))
                .into(new CustomTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        btnItem.setBackground(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });

For all image/jpg I tried, nothing is displayed. Same goes for one PNG image. Another PNG image with transparent background does display, transparency is taken into account but the color palette seems completely wrong.

The same code works fine, regardless of the image being used, for ImageButton instances.

Is there some specific code to write for Buttons?

My XML looks like this:

<Button
    android:id="@+id/btnItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textSize="10sp"
    android:text="DUMMY"/>

When using an ImageButton:

<ImageButton
    android:id="@+id/btnItem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1" />

When inspecting the bitmap with the debugger ('View bitmap' functionality), Android Studio reveals the bitmap is valid under all circumstances.


Solution

  • As @commonsware says here, recent Android Studio versions set the default theme in new projects as Theme.MaterialComponents.DayNight.DarkActionBar. So, a side effect of this is that any Button get turned into MaterialButton, and these buttons ignore the android:background attribute.

    Then, I recommend you to use androidx.appcompat.widget.AppCompatButton instead because you want to use a default Button to change that attribute. As a side note, if the previous theme didn't set, this is the project's default button when we use Button.

    Happy coding!