Android通过点击按钮改变Activity的背景颜色_个人笔记
16lz
2021-12-11
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
更多相关文章
- 无标题文章
- android 上层wifi模块调用分析
- android 设置桌面背景
- [android]在上下文菜单的选中事件中获取列表选中的元素
- Android_GPS
- android 设置桌面背景
- Android获取屏幕宽高、屏幕密度、手动计算view大小
- AlertDialog背景的修改
- Android中改变Dialog背景透明度