Android:单击时更改字体颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22675656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: change font color on click
提问by user3466562
i am trying to change the color of text inside a button.
我正在尝试更改按钮内文本的颜色。
So for example i have a button which is filled with white and the text is blue. When i click on the button i want these two colors to swap (text inside the button becomes white and the button blue).
例如,我有一个按钮,它是白色的,文本是蓝色的。当我单击按钮时,我希望这两种颜色交换(按钮内的文本变为白色,按钮变为蓝色)。
I have tried something like this:
我试过这样的事情:
<item style="@style/ButtonText_Menue_Clicked" android:drawable="@drawable/button_menue_default" android:state_focused="true"></item>
<item style="@style/ButtonText_Menue" android:drawable="@drawable/button_menue_default" ></item>
but it actually does nothing. Is there any way to do what i want, or do i have to do some stuff in the onclik event (but then there is the problem how to set the colors back when the "click is gone" )
但它实际上什么都不做。有什么方法可以做我想做的事,或者我必须在 onclik 事件中做一些事情(但是当“点击消失”时如何将颜色设置回来是个问题)
回答by Libin
Create a selector
resource in res/color
for the text color and a button selector
in res/drawable
as below...
为文本颜色创建一个selector
资源res/color
和一个按钮selector
,res/drawable
如下所示...
text_color.xml
文本颜色.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:color="#800000" />
<item
android:state_pressed="false"
android:color="#4C5" />
</selector>
button_color.xml
button_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="#4C5"/>
</shape>
</item>
<item
android:state_pressed="false">
<shape android:shape="rectangle" >
<solid android:color="#800000"/>
</shape>
</item>
</selector>
Add the button to the layout
将按钮添加到布局
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:textColor="@color/text_color"
android:background="@drawable/button_color"/>