片段中的更改按钮

时间:2018-09-14 14:25:36

标签: java android android-studio android-fragmentactivity

我在片段中有两个按钮,当我单击第一个按钮时,该按钮将变为白色,第二个按钮将变为黑色,如果单击第二个按钮,则第二个按钮将变为白色,第一个按钮也将更改变成黑色 这是我在mainActivity中的代码:

public void buttonOne(View view) {
    Button1 = findViewById(R.id.tg_btn2);
    Button2 = findViewById(R.id.tg_btn1);
    //If the Button is off
    if (!btnOneOn) {

        Button2.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
        Button1.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
        Button1.setTextColor(getResources().getColor(R.color.md_blue_grey_100));
        Button2.setTextColor(getResources().getColor(R.color.md_black_1000));
        btnTwoOn = false;
        btnOneOn = true;
        Log.i("Salam",btnOneOn.toString());
    }
    //If it is is clicked while on
    else {
        btnTwoOn = false;
        Button2.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));
    }
}

public void buttonTwo(View view) {
    Button2 = findViewById(R.id.tg_btn2);
    Button1 = findViewById(R.id.tg_btn1);
    //If the Button is off
    if (!btnTwoOn) {

        Button1.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
        Button2.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
        btnOneOn = false;
        btnTwoOn = true;
    }
    //If it is is clicked while on
    else {
        btnOneOn = false;
        Button1.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));
    }

但无法正常工作 你有什么建议?

1 个答案:

答案 0 :(得分:0)

问题可能出在这段代码中

setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900))

尝试这样

setBackgroundColor(ContextCompat.getColor(context, R.color.md_blue_grey_900))