我正在嘗試更改按鈕上文本的顏色。這是我的代碼Android onClick不會更改按鈕的文本顏色
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.graphics.Color;
public class ColorPatternGameActivity extends Activity implements OnClickListener {
protected Button button1;
protected Button button2;
protected Button button3;
protected Button button4;
protected TextView test;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.b1);
Button button2 = (Button)findViewById(R.id.b2);
Button button3 = (Button)findViewById(R.id.b3);
Button button4 = (Button)findViewById(R.id.b4);
TextView test = (TextView)findViewById(R.id.test);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
test.setText("testing");
}
@Override
public void onClick(View v) {
if (v == button1) {
test.setText("Red");
button1.setTextColor(Color.RED);
}
else if (v == button2) {
button2.setTextColor(Color.GREEN);
test.setText("Green");
}
else if (v == button3) {
button3.setTextColor(Color.BLUE);
test.setText("Blue");
}
else if (v == button4) {
button4.setTextColor(Color.YELLOW);
test.setText("Yellow");
}
}
}
單擊按鈕不會更改文本或顏色。我之前已經實現了onClick,它工作的很好,這讓我更加困惑,爲什麼它不工作。
如果它幫助我的XML的樣本,我宣佈一個按鈕:
<Button
android:id="@+id/b1"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"/>
Facepalm,其總是簡單的東西從來沒有大的東西。謝謝wsanville。 – Phil 2012-04-20 19:21:45