简体   繁体   English

Android RelativeLayout更改颜色onClick

[英]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: 我尝试使用绑定到background属性的选择器,如下所示:

<?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? 有任何想法吗?

Try the following steps: 请尝试以下步骤:

In res --> values folder create color.xml with the content: res - > values文件夹中创建带有内容的color.xml

<?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: 由于选择器中的<item>标记需要一个drawable属性或定义drawable的子标记,因此layout_selector.xml文件(保存在res - > drawable中 )应如下所示:

<?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" ) 另外,如前所述,相对布局应该是可点击的( android:clickable="true"

and its background set as android:background="@drawable/layout_selector" 并将其背景设置为android:background="@drawable/layout_selector"

Hope it helps 希望能帮助到你

Use selector on the android:background attribute of your RealtiveLayout. 在RealtiveLayout的android:background属性上使用选择器 Also make the layout clickable (through android:clickable="true" ). 还可以使布局可点击(通过android:clickable="true" )。

Layouts are not displayed into the screen. 布局不会显示在屏幕上。 They only may to conrain views. 他们只能提出意见。 You shold add some View and then add onClick listener to that view. 您将添加一些View,然后将onClick侦听器添加到该视图。

Possible dublicate: Android clickable layout 可能的dublicate: Android可点击布局

把这个layout_selector.xml放在drawable文件夹即(res> drawable> layout_selector.xml)然后设置android:background="@drawable/layout_selector"而不是android:background="@color/layout_selector"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM