Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

java - Android RelativeLayout change color onClick

How do i change the color of a Relative Layout i use as a clickable on Click like the normal Button? Like i want a visual feedback the layout was pressed.

I tried it with a selector bound to the background property like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:color="@android:color/black"/>
   <item android:state_pressed="true" android:state_enabled="false" android:color="@android:color/black" />
   <item android:color="@android:color/white"/>
</selector>

and used it in the Layouts backround...

android:background="@color/layout_selector"

but this gives me an Inflate Exception...

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the following steps:

In res --> values folder create color.xml with the content:

<?xml version="1.0" encoding="utf-8"?>
<resources>     
    <color name="black">#000000</color> 
    <color name="white">#ffffff</color>
</resources>

As <item> tag in selector requires a drawable attribute or child tag defining a drawable, your layout_selector.xml file (which is saved in res --> drawable) should look like this:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
    <item android:state_focused="true" android:drawable="@color/black"/> 
    <item android:state_pressed="true" android:state_enabled="false" android:drawable="@color/black" />
    <item android:drawable="@color/white"/> 
 </selector>

Also, as said earlier, the relative layout should be clickable (android:clickable="true")

and its background set as android:background="@drawable/layout_selector"

Hope it helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...