Android通過點擊按鈕改變Activity的背景顏色_個人筆記

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"

實現出來就是點哪個按鈕,背景就變什麼色。

更多文章:http://blog.csdn.net/qq_26849491

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章