1

I have the following image button in my XML layout

<ImageButton
    android:id="@+id/show_only_checked"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_weight="0"
    android:src="@android:drawable/arrow_down_float"
    tools:src="@android:drawable/arrow_down_float" />

Great. Works perfect. But I want to toggle it in the onClick() event to the up version of this drawable in code. Everytime the user clicks the button, I want to toggle back and forth between the up and down arrow. I appear to be too dense to figure this out. I have tried the following code, with no luck.

if (ShowOnlyChecked) {
    view.setBackground(Drawable.createFromPath("@android:drawable/arrow_up_float"));
} else {
    view.setBackground(Drawable.createFromPath("@android:drawable/arrow_down_float"));
}

Any help would be appreciated.

Part of my problem was how to reference "android.R..." to the drawable. The other was which method to call.

JJJones_3860
  • 1,382
  • 2
  • 15
  • 35
  • Possible duplicate of [Imagebutton change programmatically?](https://stackoverflow.com/questions/14233062/imagebutton-change-programmatically) – CodeWithVikas Nov 05 '19 at 16:44
  • Hii There is lot of similar question already answered. https://stackoverflow.com/questions/14233062/imagebutton-change-programmatically – CodeWithVikas Nov 05 '19 at 16:46
  • Check this too https://stackoverflow.com/questions/16526112/how-to-replace-change-image-button-programmatically-android – CodeWithVikas Nov 05 '19 at 16:46

3 Answers3

2

Your code will change the view's background image.

Here is how to set the button image:

((ImageButton) view).setImageResource(R.drawable.arrow_down_float);
matdev
  • 4,115
  • 6
  • 35
  • 56
1

try:

 imageButton.setBackgroundResource(android.R.drawable.arrow_up_float);
Ehsan msz
  • 1,774
  • 2
  • 13
  • 26
1

As you are using ImageButton component, you set things in runtime wrongly, because Drawable.createFromPath provides a path to drawable as say absolute path or the desired path. If you want to set an arrow, then try to add different resolution images of arrow based on resource folder or youId.setBackgroundResource(android:R.drawable.id) or get images from here

https://material.io/resources/icons/?style=baseline

Ankit Tale
  • 1,924
  • 4
  • 17
  • 30