简体   繁体   English

点击后,android-change按钮背景颜色

[英]android-change button background color after clicked

Problem: I want to change the background color of a button after it has been pressed. 问题:我想在按下按钮后更改按钮的背景颜色。

It's a simple problem, but I have spent a lot of time googling this and I can't seem to find a solution. 这是一个简单的问题,但我花了很多时间在谷歌上搜索,我似乎无法找到解决方案。 They all refer to the same XML that appears below. 它们都引用下面显示的相同XML。

My XML is as follows: 我的XML如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/black_button_pressed" android:state_focused="true" />
    <item android:drawable="@drawable/black_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/black_button_normal"/>
</selector>

So, when a person hovers over a button, it'll appear grayed out. 所以,当一个人盘旋在按钮上时,它会显示为灰色。 When a person clicks on a button, the button's background should be grayed out after the click, but I can't seem to get it grayed out. 当一个人点击一个按钮时,按钮的背景应该在点击后显示为灰色,但我似乎无法将其显示为灰色。 It returns to the normal state after the press. 按下后返回正常状态。

Do you guys have any tips and/or pointers to help me? 你们有任何提示和/或指示来帮助我吗?

In android, state of the UI will not persist after the event is completed. 在android中,事件完成后UI的状态不会持久存在。 For example, you can handle the button click event and highlight the button but it returns to its normal state once the Up event is fired. 例如,您可以处理button click事件并突出显示按钮,但一旦触发Up事件,它将返回到正常状态。 So, the only option as far as i know is, change the background of the button by setting a different drawable resource . 因此,据我所知,唯一的选择是通过设置不同的drawable resource更改按钮的背景。

btn.setBackgroundResource(R.drawable.btn_selected_blue);

This works (in your onClick handler): 这有效(在你的onClick处理程序中):

button.setBackgroundResource(R.drawable.button_selected);

There may be a nicer way however. 然而,可能有一个更好的方式。

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

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