点击第二个按钮后的颜色开关

时间:2011-05-16 20:13:55

标签: android

如何在第二次点击后使用“switch statement”将颜色从按钮1切换到按钮2? 这些是我点击的2个按钮

private int lCount = 0;
private int rCount = 0;
private int myCount = lCount & rCount;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL);
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);

countButtonPlusL.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
             countTextViewPlusL.setBackgroundColor(0xffffffff);}
          else countTextViewPlusL.setBackgroundColor(0x00000000);
        lCount++;
        if (lCount >-1)
        countTextViewPlusL.setText("" + lCount);
    }
});


final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR);
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

countButtonPlusR.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        myCount++;
          if(myCount%2 == 0){
            countTextViewPlusR.setBackgroundColor(0xffffffff);}
          else countTextViewPlusR.setBackgroundColor(0x00000000);
        rCount++;
        if (rCount >-1)
        countTextViewPlusR.setText("" + rCount);
    }
});

2 个答案:

答案 0 :(得分:1)

您正在增加监听器中的lCount和/或rCount,但您正在测试myCount的奇偶校验。这就是事情不会改变的原因。

答案 1 :(得分:0)

为什么不尝试这样的事情?

private int lCount = 0;
private int rCount = 0;
private int myCount = 0;

final TextView countTextViewPlusL = (TextView) findViewById(R.id.TextViewCountL); 
final Button countButtonPlusL = (Button) findViewById(R.id.ButtonCountPlusL);
final TextView countTextViewPlusR = (TextView) findViewById(R.id.TextViewCountR); 
final Button countButtonPlusR = (Button) findViewById(R.id.ButtonCountPlusR);

View.OnClickListener listener = new View.OnClickListener() {
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.ButtonCountPlusR:
                rCount++;
                break;
            case R.id.ButtonCountPlusL:
                lCount++;
                break;
        }
        myCount = lCount + rCount;
        if(myCount % 2 == 0) {
            //invert colors here
        }
    }
});

countButtonPlusL.setOnClickListener(listener);
countButtonPlusR.setOnClickListener(listener);

将所有计数器初始化为零,然后检查每次单击哪个按钮被单击,增加其计数器,将myCount设置为等于左右计数器的总和,然后检查是否是第二次单击。在该检查中,反转TextView颜色。