How do I set the selected state of an image button with xml
-
19-09-2019 - |
Question
I have an image button as defined below.
<ImageButton
android:text="Play"
android:src="@drawable/playpause"
android:background="@drawable/opaque"
android:gravity="center_horizontal"
android:id="@+id/player_ctrl_btn"
android:layout_width="fill_parent"
android:padding="0px"
android:layout_height="wrap_content" />
I want to set the default state of the button to be selected. So in code I would say:
playBtn.setSelected(true);
Is it possible to do this in xml?
Solution
It doesn't look like you can -- sorry!
OTHER TIPS
A newer solution to the problem would be to use DataBinding
.
- Create a
@BindingAdapter
(somewhere in your code):
@BindingAdapter("is_selected")
fun setSelected(view: View, selected: Boolean) {
view.isSelected = selected
}
- Use
DataBinding
in yourxml
<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}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow