Issue
What I want:
An ImageView with a transparent background. When it is clicked, its background should turn blue, and should remain blue until something else is clicked. I am using state-list drawable for it.
What is happening:
The code is given as follows. The problem is that the background does turn blue, but it does not remain blue. So I thought it is because android:state_pressed
just represents the moment when the widget is being clicked. So I also added android:state_selected="true"
to button_state_list_drawable.xml
right after android:state_pressed="true"
. What happened then is that the background stopped turning blue even when the imageview is being clicked.
How do I fix this?
ImageView
defined in XML like this:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fragment_imageView"
android:src="@drawable/ic_photo"
android:background="@drawable/button_state_list_drawable"
android:clickable="true" />
The button_state_list_drawable.xml
is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/button_pressed_state_drawable"
android:state_pressed="true"
android:state_selected="true" />
<item android:drawable="@drawable/button_enabled_state_drawable" />
</selector>
The button_pressed_state_drawable.xml
is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size android:width="50dp"
android:height="50dp" />
<padding android:left="25dp"
android:right="25dp"
android:top="25dp"
android:bottom="25dp" />
<stroke android:color="#fff"
android:width="1dp" />
<solid android:color="#1aafd0" />
</shape>
The button_enabled_state_drawable.xml
is:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size android:width="50dp"
android:height="50dp" />
<padding android:left="25dp"
android:right="25dp"
android:top="25dp"
android:bottom="25dp" />
<stroke android:color="#fff"
android:width="1dp" />
<solid android:color="@android:color/transparent" />
</shape>
Solution
I recently had this problem, and this is what I did.
In your button_state_list_drawable.xml, add this somewhere before you default state item:
<item android:drawable="@drawable/button_pressed_state_drawable"
android:state_selected="true"
android:state_pressed="false" />
Also remove android:state_selected="true"
from your state_pressed
item.
Then in the beginning of your click listener for the ImageView
, write
yourImageView.setSelected(true);
This had solved my problem. Hope it helps you.
Answered By - NXA
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.