简体   繁体   English

按下时按钮颜色会发生变化,但是当我进行下一次迭代时,按钮颜色不会变为默认背景颜色

[英]Button color is changing when pressed but when i go for next iteration that button color is not going to default background color

I'm very new to the android app development.我对android应用程序开发很陌生。 Currently I'm doing simple android quiz app with 10 questions.目前我正在做一个有 10 个问题的简单 android 测验应用程序。

My default options button color is white.我的默认选项按钮颜色是白色。 When user is answered a question out of three options, i want to show them the selected option by changing the option button color( by using setBackground color in setOnClickListener method).当用户从三个选项中回答一个问题时,我想通过更改选项按钮颜色(通过在 setOnClickListener 方法中使用 setBackground 颜色)向他们显示所选选项。

But my problem is, My first question selected option color is coming to second question also without selecting answer.但我的问题是,我的第一个问题选择的选项颜色也没有选择答案就来到了第二个问题。 I dont know how to cancel the background color on each iteration.我不知道如何在每次迭代时取消背景颜色。

Thanks in Advance!!!提前致谢!!!

    Option1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            selected_option = 0;
            question_id = 1;
            Option1.setBackgroundColor(R.color.Yellow);
            updateSelectedAnswer(selected_option, question_id);
        }
    });

We can define ColorStateList resource .我们可以定义ColorStateList 资源

You can do it using as below (feel free to change color according to your need):您可以使用以下方法进行操作(可根据需要随意更改颜色):

Create a file in res/color/button_background_selector.xml :res/color/button_background_selector.xml创建一个文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="@android:color/red" /> <!-- pressed -->
    <item android:state_focused="true"
          android:color="@android:color/blue" /> <!-- focused -->
    <item android:state_hovered="true"
          android:color="@android:color/green" /> <!-- hovered -->
    <item android:color="@android:color/yellow" /> <!-- default -->
</selector>

Then, use it as below:然后,使用它如下:

<Button
    ...
    android:background="@color/button_background_selector" />

当您在显示下一个问题之前更改按钮的颜色时,如下代码所示... Option1.setBackgroundColor(R.color.white);

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

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