改变按钮的颜色

时间:2014-12-22 04:16:38

标签: java android button colors

我的应用程序有四个按钮。我试图让按钮的颜色变为一种颜色,如果按特定顺序按下它们,如果以不同的顺序按下它们,则将它们更改为不同的颜色。现在我的代码是这样的:

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
    }
}

现在我收到一个创建按钮的NullPointerException。我认为这是因为按钮不是在onCreate方法中创建的。但是,如果我将按钮放在onCreate方法中,则无法在checkOrder方法中访问它们。我将如何从不同的方法改变颜色?我知道过去曾经问过类似的问题,但我没有找到一个我面临同样问题的问题。

1 个答案:

答案 0 :(得分:3)

在类级别声明按钮并在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);
    }
}

在您想要使用的任何地方使用

之后
相关问题