Android在xml布局文件中修改Button颜色,按钮颜色却不改变

Android,你可以使用Fragment来创建自定义界面,并结合四个Button来实现点击按钮背景颜色的变化。首先,你需要在Fragment布局文件添加四个Button。然后,为每个Button设置一个监听器,当按钮被点击时,会触发一个方法更改其背景颜色。 以下是基本步骤: 1. **在XML布局文件** (activity_main.xml 或 fragment_layout.xml) 添加四个Button,例如: ```xml <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 2" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 3" /> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button 4" /> ``` 2. **在Fragment内部** (MyFragment.java 或 MainActivity.java),给每个Button设置OnClickListener: ```java public class MyFragment extends Fragment { private Button button1, button2, button3, button4; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); button1 = view.findViewById(R.id.button1); button2 = view.findViewById(R.id.button2); button3 = view.findViewById(R.id.button3); button4 = view.findViewById(R.id.button4); // 设置点击事件监听 button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeBackgroundColor(v.getId()); } }); // 添加其他三个按钮的监听器,代码类似 button2.setOnClickListener(...); button3.setOnClickListener(...); button4.setOnClickListener(...); return view; } // 改变按钮背景颜色的通用方法 private void changeBackgroundColor(int buttonId) { switch (buttonId) { case R.id.button1: button1.setBackgroundColor(Color.RED); // 示例:设置红色 break; case R.id.button2: button2.setBackgroundColor(Color.GREEN); break; case R.id.button3: button3.setBackgroundColor(Color.BLUE); break; case R.id.button4: button4.setBackgroundColor(Color.YELLOW); break; } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值