根据其状态更改所选按钮的背景颜色

时间:2018-04-20 14:15:17

标签: android button background-color

我看到一些帖子有类似的问题,但它们仍然与我的问题不同。我在Android Studio中制作绘画应用程序,我想指出用户选择的选项(无论是移动工具,铅笔等)。这是图片:

Screenshot

因此,我想在选择按钮时更改按钮的背景颜色,并在选择另一个按钮时将其恢复为默认颜色。
我尝试使用XML选择器,但后来我看到现在有一​​个常规按钮的“selected”属性。这些是常规按钮。解决这个问题的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

试试这段代码(button_selector.xml,把它放在你的drawable文件夹中)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/holo_blue_dark" android:state_selected="true"></item>
<item android:drawable="@android:color/holo_blue_dark" android:state_pressed="true"></item>
<item android:drawable="@android:color/darker_gray"></item>

</selector>

XML

<Button
    android:background="@drawable/button_selector" />

答案 1 :(得分:1)

您可以使用类变量来跟踪当前选定的按钮,并检测何时选择了新按钮。然后,您将执行“选择”新按钮的操作,并“取消选择”前一个按钮。例如:

private Button mSelectedButton;

private void setOnClickListeners() {
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Button clickedButton = (Button) view;

            //in case no button is selected, this will only "select" the clickedButton
            if (mSelectedButton == null) mSelectedButton = clickedButton;

            //previous selected button (should return to original state)
            mSelectedButton.setBackgroundColor(R.color.original_state);

            //your new selected button
            clickedButton.setBackgroundColor(R.color.selected_state);

            mSelectedButton = clickedButton; //save currently selected button
        }
    };

    yourButton1.setOnClickListener(listener);
    yourButton2.setOnClickListener(listener);
    yourButton3.setOnClickListener(listener);
    ...
}