3

ボタンのテキストの色を onClick で変更する方法を探しています。選択したボタンのテキストの色を変更し、他のボタンのテキストをデフォルトの色に戻したいです。この方法(以下)は非常に非効率的です。それについてもっと良い方法はありますか?また、onClick で元の色に戻すにはどうすればよいですか?

public void onClick(View v) {
    switch (v.getId()){
        case R.id.button1:
            TextView textView1 = (TextView) findViewById(R.id.button1);
            textView1.setTextColor(Color.RED);
            logLevel = "E";
            //Change the rest to default (white)
        break;
        case R.id.button2:
            TextView textView2 = (TextView) findViewById(R.id.button2);
            textView2.setTextColor(Color.RED);
            logLevel = "W";
            //Change the rest to white
        break;
        case R.id.button3:
            TextView textView3 = (TextView) findViewById(R.id.button3);
            textView3.setTextColor(Color.RED);
            logLevel = "D";
            //Change the rest to white
        break;
        case R.id.button4:
            TextView textView4 = (TextView) findViewById(R.id.button4);
            textView4.setTextColor(Color.RED);
            logLevel = "I";
            //Change the rest to white
        break;
    }

    retrieveLog(logLevel);
}
4

2 に答える 2

11

それについてもっと良い方法はありますか?

ステップ #1:TextView[] buttonsアクティビティまたはフラグメントにデータ メンバーを追加する

ステップ #2:onCreate()の後setContentView()で、ボタンごとに 1 回、4 回呼び出しfindViewById()、各ボタンをbuttons配列に配置します。

ステップ #3: 次onClick()のように書き換えます。

for (TextView button : buttons) {
  if (button==v) {
    button.setTextColor(Color.RED);
  }
  else {
    button.setTextColor(Color.WHITE);
  }
}
于 2013-06-10T19:17:48.657 に答える