Android通過點擊按鈕改變Activity的背景顏色_個人筆記
今天學習了通過兩個按鈕的點擊監聽事件。
private Button button1;
private Button button2;
private LinearLayout layout;
先聲明按鈕、佈局LinearLayout
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1= (Button) this.findViewById(R.id.button1);//獲取
button2= (Button) this.findViewById(R.id.button2);//獲取
layout= (LinearLayout) this.findViewById(R.id.layout);//獲取
button1.setOnClickListener(new View.OnClickListener() { //事件
@Override
public void onClick(View v) {
layout.setBackgroundColor(Color.RED);
((Button)v).setText("背景紅了");
}
});
button2.setOnClickListener(new View.OnClickListener() { //事件
@Override
public void onClick(View v) {
layout.setBackgroundColor(Color.BLUE);
((Button)v).setText("背景藍了");
}
});
}
以下是xml的代碼
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="紅"
android:id="@+id/button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="藍"
android:id="@+id/button2" />
在這裏需要注意的是要明確LinearLayout的ID
android:id="@+id/layout"
實現出來就是點哪個按鈕,背景就變什麼色。