简体   繁体   English

改变按钮的颜色

[英]Changing Color of Buttons

My application has four buttons. 我的应用程序有四个按钮。 I am trying to have the color of the buttons change to one color if they are pressed in a certain order and have them change to a different color if they are pressed in a different order. 我试图让按钮的颜色变为一种颜色,如果按特定顺序按下它们,如果以不同的顺序按下它们,则将它们更改为不同的颜色。 Right now my code is this: 现在我的代码是这样的:

public class MainActivity extends Activity {

int b1 = (int) (Math.random() * 10.0);
int b2 = (int) (Math.random() * 10.0);
int b3 = (int) (Math.random() * 10.0);
int b4 = (int) (Math.random() * 10.0);
int last = 0;
int[] nums = { b1, b2, b3, b4 };
int i = 0;
String res = "";
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);

private void checkOrder(int value) {
    if (value == nums[i]) {
        if (i == 3) {
            //DO SOMETHING ELSE
        } else {
            if(value==b1){
                button1.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b2){
                button2.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b3){
                button3.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b4){
                button4.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }
            i++;
        }
    } else {
        //DO SOMETHING ELSE
    }
}

Right now I am getting a NullPointerException where the buttons are created. 现在我得到一个创建按钮的NullPointerException。 I think this is because the buttons are not created in the onCreate method. 我认为这是因为按钮不是在onCreate方法中创建的。 However, if I do put the buttons in the onCreate method they cannot be accessed in the checkOrder method. 但是,如果我将按钮放在onCreate方法中,则无法在checkOrder方法中访问它们。 How would I go about changing their colors from a different method? 我将如何从不同的方法改变颜色? I know that similar questions have been asked in the past, but I have not found one with the same problem I am facing. 我知道过去曾经问过类似的问题,但我没有找到一个我面临同样问题的问题。

Declare your buttons at class level and initialize them in onCreate method 在类级别声明按钮并在onCreate方法中初始化它们

Class Demo extends Activity{

    Button button1,button2,button3,button4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);
    }
}

After this use wherever you want to use 在此之后使用您想要使用的任何地方

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

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