检测单击了哪个按钮

时间:2018-08-10 07:53:49

标签: java android

我的页面上有3个按钮: 红色,蓝色和绿色 我如何检测单击了哪个按钮 我要为下一页使用背景色(红色,蓝色或绿色) 这是我在主页上的代码:

public void color(View view) {
    Intent color= new Intent(this, colorPage.class);
    Click(view);
    String What_color = view.toString();
    color .putExtra("What_color",What_color);
    startActivity(colorPage);
}

private void Click(View view1) {
    int id = view1.getId();
        }

}

这是我在colorPage中的代码:

Bundle What_color = getIntent().getExtras();
    if (What_color != null) {
        String mycol = What_color.getString("What_color");
        TextView result = (TextView) findViewById(R.id.tResult);
        result.setText(mycol);
    }

我在textView中看到此代码: android.support.v7.widget.AppCompatButton {366bb1b VFED..C。 ... P .... 0,0-728,114#7f070023 app:id / 红色

或此代码: ndroid.support.v7.widget.AppCompatButton {366bb1b VFED..C。 ... P .... 0,0-728,114#7f070023 app:id / 蓝色

请帮助我

2 个答案:

答案 0 :(得分:1)

为每个按钮及其ID添加一个侦听器。

Button buttonOne = (Button) findViewById(R.id.YOURBUTTONID);
buttonOne.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
            //Do change the color.
    }
});

//This code changing background on your activity but You have to give color as a hexadecimal 
public void setActivityBackgroundColor(int color) {
    View view = this.getWindow().getDecorView();
    view.setBackgroundColor(color);
}

答案 1 :(得分:0)

    you can create a global string like 

    String detectBtnStr = "";


    private void Click(View view1) {
        int id = view1.getId();

    switch(id){

    case: R.id.red_btn:
    detectBtnStr = "red";
    break;

    case: R.id.blue_btn:
    detectBtnStr = "blue";
    break;


    case: R.id.green_btn:
    detectBtnStr = "green";
    break;
    }

            }


and when come back then check with detectBtnStr like


 if (detectBtnStr.equals("red")) {
            // do your code}
        else if (detectBtnStr.equals("blue")) {
                // do your code
            }
            else if (detectBtnStr.equals("green")){
            // do your code
            }

希望这会对您有所帮助。