iT邦幫忙

0

關於android點擊按鈕計數加一加到六時重新計數

`TextView mTotal2;
TextView mChinese2;
TextView mJapan2;
TextView mSmail2;
TextView mLove2;
Button mTotal1;
Button mChinese1;
Button mJapan1;
Button mSmail1;
Button mLove1;
int counter = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTotal1.setOnClickListener(this);
    mChinese1.setOnClickListener(this);
    mJapan1.setOnClickListener(this);
    mSmail1.setOnClickListener(this);
    mLove1.setOnClickListener(this);
     @Override
public void onClick(View v) {
    counter++;
    mTotal2.setText(String.valueOf(counter));
    counter2++;
    mChinese2.setText(String.valueOf(counter2));
    counter3++;
    mJapan2.setText(String.valueOf(counter3));
    counter4++;
    mSmail2.setText(String.valueOf(counter4));
    counter5++;
    mLove2.setText(String.valueOf(counter5));`
    
    

現在的部分是我弄5個按鍵想要各自做累加,但如上面的程式碼我只要隨便按其中一個按鈕,不管怎麼樣都會在五個textview上加一,而我想要在加到六的時候歸零,這部分沒做出來,還請各位幫幫忙

1
fysh711426
iT邦新手 3 級 ‧ 2017-11-16 00:44:15

[Android] 簡易Button事件處理
要把 Click 事件分開寫

mTotal1.setOnClickListener(new Button.OnClickListener(){ 
    @Override
    publicvoid onClick(View v) {
        counter++;
        mTotal2.setText(String.valueOf(counter));
    }
});
mChinese1.setOnClickListener(new Button.OnClickListener(){ 
    @Override
    publicvoid onClick(View v) {
        counter2++;
        mChinese2.setText(String.valueOf(counter2));
    }
});

然後加到六歸零可以這樣寫

mTotal1.setOnClickListener(new Button.OnClickListener(){ 
    @Override
    publicvoid onClick(View v) {
        counter++;
        counter = counter % 7;
        mTotal2.setText(String.valueOf(counter));
    }
});
0
海綿寶寶
iT邦超人 1 級 ‧ 2017-11-16 07:59:49

另一種改法

    if (++counter > 6) { counter = 0; }
    mTotal2.setText(String.valueOf(counter));
    if (++counter2 > 6) { counter2 = 0; }
    mChinese2.setText(String.valueOf(counter2));
    if (++counter3 > 6) { counter3 = 0; }
    mJapan2.setText(String.valueOf(counter3));
    if (++counter4 > 6) { counter4 = 0; }
    mSmail2.setText(String.valueOf(counter4));
    if (++counter5 > 6) { counter5 = 0; }
    mLove2.setText(String.valueOf(counter5));
0
andy6804tw
iT邦新手 5 級 ‧ 2017-11-16 09:52:36

button可以寫在一起並用switch判斷是哪個view被觸擊,你原本寫這樣沒錯,可以免於每個點擊事件分開寫的麻煩也很清楚統一管理點擊事件,各有優缺點所以要視情況使用

 @Override
    public void onClick(View v) {

        switch (v.getId()){
            // v這個參數讀出Button的id
            case R.id.mTotal1:
                
                break;
            case R.id.mChinese1:
                
                break;
            case R.id.mJapan1: {
                
                break;
            }
            ...
            ...
            ...
        }
    }

此外歸零善用%運算法求餘數就行了

我要發表回答

立即登入回答