How do I set the selected state of an image button with xml How do I set the selected state of an image button with xml xml xml

How do I set the selected state of an image button with xml


A newer solution to the problem would be to use DataBinding.

  1. Create a @BindingAdapter (somewhere in your code):
@BindingAdapter("is_selected")fun setSelected(view: View, selected: Boolean) {    view.isSelected = selected}
  1. Use DataBinding in your xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">    <data>    </data>    <ImageButton        android:id="@+id/player_ctrl_btn"        is_selected="@{true}"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:background="@drawable/opaque"        android:gravity="center_horizontal"        android:padding="0px"        android:src="@drawable/playpause"        android:text="Play" /></layout>

IMPORTANT: remember that you need to use DataBinding here. So you cannot simply call add is_selected="true" (because it will fail not telling you about it), you need to add is_selected="@{true}"


No need to create BindingAdapter method, just enable DataBidning and type:

<layout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"><data></data><ImageButton    android:id="@+id/player_ctrl_btn"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:background="@drawable/opaque"    android:gravity="center_horizontal"    android:padding="0px"    android:src="@drawable/playpause"    android:text="Play"    app:selected="@{true}" /></layout>