1、点击Button改变页面背景色

  通过Button改变页面背景色,首先新建相应的对象,让后绑定到Layout上的元素。

1  final RelativeLayout layout = (RelativeLayout)this.findViewById(R.id.layout);
2  final Button btnRed = (Button)this.findViewById(R.id.btnRed);

  然后向新建的按钮增加单机事件。

 btnRed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                layout.setBackgroundColor(Color.RED);
                ((Button)view).setText("Is Red");
            }
        });

  完整代码: 

 1 public class MainActivity extends AppCompatActivity {
 2 
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         this.setTitle("Button");
 7         setContentView(R.layout.activity_main);
 8 
 9         final RelativeLayout layout = (RelativeLayout)this.findViewById(R.id.layout);
10         final Button btnRed = (Button)this.findViewById(R.id.btnRed);
11         final Button btnGreen = (Button)this.findViewById(R.id.btnGreen);
12         final Button btnBlue = (Button)this.findViewById(R.id.btnBlue);
13 
14         btnRed.setOnClickListener(new View.OnClickListener() {
15             @Override
16             public void onClick(View view) {
17                 btnGreen.setText("Green");
18                 btnBlue.setText("Blue");
19                 layout.setBackgroundColor(Color.RED);
20                 ((Button)view).setText("Is Red");
21             }
22         });
23         btnGreen.setOnClickListener(new View.OnClickListener() {
24             @Override
25             public void onClick(View view) {
26                 btnRed.setText("Red");
27                 btnBlue.setText("Blue");
28                 layout.setBackgroundColor(Color.GREEN);
29                 ((Button)view).setText("Is Green");
30             }
31         });
32         btnBlue.setOnClickListener(new View.OnClickListener() {
33             @Override
34             public void onClick(View view) {
35                 btnRed.setText("Red");
36                 btnGreen.setText("Green");
37                 layout.setBackgroundColor(Color.BLUE);
38                 ((Button)view).setText("Is Blue");
39             }
40         });
41 
42     }
43 }
MainActivity.java

相关文章: