按下时更改按钮文本颜色
我已将按钮设置为透明,因此我希望在按下按钮时更改按钮文本颜色。是否可以仅使用 xml 文件来完成此操作?
I have made my button transparent so I would like to have the button text color change when the button is pressed. Is it possible to do this using just xml files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,你可以这样做:
layout/main_layout.xml:
color/button_text_color.xml:
Yes, you can do it like that:
layout/main_layout.xml:
color/button_text_color.xml:
请参阅本文档中名为状态列表的部分...可绘制资源。
您可以定义两个不同的
Button
xml 文件,一个用于透明的“默认”状态,另一个将按钮设置为红色,用于“按下”状态。然后,您定义一个选择器
,用于在不同状态下切换可绘制资源。编辑:根据 devunwired 的评论,颜色状态列表资源可能更适合仅更改颜色而不是可绘制本身。
See the section called State List in this bit of documentation...Drawable Resources.
You can define two different
Button
xml files one for the transparent 'default' state and another with the button as Red for your 'pressed' state. You then define aselector
which switches the drawable resources in the different states.EDIT: As per devunwired's comment the Color State List resource is probably more suitable for just changing colours rather than the drawable itself.
我喜欢 Konstantin Burov 在另一期中提出的解决方案:Android 自定义按钮;更改文本颜色
实际上,您可以管理更多状态,而不仅仅是按下和正常。但应该能解决问题。
然后,您可以在按钮中使用可绘制的选择器来更改文本颜色属性,如下所示。请注意,下面示例中的选择器名为“button_text_color”
使用相同的drawable方法你也可以解决按钮的背景颜色。请记住,在选择器中,您需要使用“android:drawable”属性,而不是使用“android:color”属性,如下所示。
然后在按钮本身中执行此操作,请注意,这次选择器名称是“button_background”
I like the solution proposed by Konstantin Burov in the other issue: Android customized button; changing text color
You can actually manage more states than just pressed and normal. But it should solve the problem.
Then you can use that selector drawable in your button changing the text color attribute like below. Note that the selector in the example below is named "button_text_color"
Using the same drawable approach you can also solve the background color of the button. Just remember that in the selector instead of using the "android:color" attribute you need to use the "android:drawable" attribute like below.
And then in the button itself do, note that this time the selector name is "button_background"
您必须在代码中执行此操作。试试这个:
声明:
You have to do it in your code. Try this:
Declare:
您必须在
textColor
属性中设置@drawable
xml 资源示例如下:Android自定义按钮;改变文字颜色
You must set
@drawable
xml resource intextColor
attributteHere is example: Android customized button; changing text color