【问题标题】:Android: change font color on clickAndroid:点击更改字体颜色
【发布时间】:2014-05-05 17:17:33
【问题描述】:

我正在尝试更改按钮内文本的颜色。

例如,我有一个按钮,该按钮用白色填充,文本为蓝色。当我单击按钮时,我希望这两种颜色交换(按钮内的文本变为白色,按钮变为蓝色)。

我尝试过这样的事情:

 <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>

但它实际上什么也没做。 有什么方法可以做我想做的事,还是我必须在 onclik 事件中做一些事情(但是当“点击消失”时,如何将颜色设置回来的问题)

【问题讨论】:

  • 据我所知,您需要在 onClick 中执行此操作。非常简单的代码。
  • 我该如何改回来?
  • 还有一个问题,即当您完成点击时文本会发生变化。但我希望在释放按钮之前更改按钮文本(释放按钮后调用 onclick)
  • 你可以使用ColorStateList,并将其设置为textColor
  • 我之前没用过。我会调查它并检查它是否可以帮助我做我想做的事情:) 谢谢你的回答:)

标签: android button text colors


【解决方案1】:

res/color 中为文本颜色创建一个selector 资源,在res/drawable 中创建一个按钮selector,如下所示...

text_color.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

<?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>

将按钮添加到布局中

 <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"/>

【讨论】:

  • 太好了,这正是我要找的东西,谢谢
  • text_color.xml 是Color State List Resource,所以我认为将它放在color 目录中比在drawable 中更好,因为将drawable 设置为textColor 会令人困惑。
猜你喜欢
  • 2017-01-27
  • 2021-10-08
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2015-10-29
  • 2010-10-28
  • 1970-01-01
相关资源
最近更新 更多