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

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