Search code examples
androidandroid-drawableimagebutton

ImageButton set drawable using @android:drawable/ programmatically


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.


Solution

  • 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);