我正在尝试更改按钮上文本的颜色。这是我的代码
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"/>