在Android应用程序中,我想更改Button
的背景颜色。
我尝试将“背景”属性从android:Drawable/btn_default_holo_light
更改为#FFFF00
,然后根据需要获得了新颜色。缺点是Button
的形状也发生了变化:原始Button
的边缘消失了,彩色区域越来越宽,完全填满了它的区域。
如何仅更改背景颜色而不更改Button
的外观?
答案 0 :(得分:4)
您可以以编程方式设置按钮背景
b= (Button) findViewById(R.id.button1);
b.setBackgroundColor(Color.RED);
使用自定义drawables设置背景。
可绘制文件夹中的buttonbkg.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/pressed" />
<item android:state_focused="false"
android:drawable="@drawable/normal" />
</selector>
普通文件夹中的.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke android:width="3dp"
android:color="#0FECFF" /><!-- #330000FF #ffffffff -->
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
pressed.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FF1A47"/>
<stroke android:width="3dp"
android:color="#0FECFF"/>
<padding android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
在您的activity_main.xml
中 <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:background="@drawable/buttonbkg" or android:background="#0EFFFF"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Click" />
答案 1 :(得分:0)
您不能像这样更改背景颜色,因为Button形状是在其背景图像中定义的。如果您想要不同的颜色,则需要创建自己的背景。只需谷歌“Android自定义按钮”,你会发现大量的信息和教程。
答案 2 :(得分:0)
按钮标记中只有android:backgroud=#FFFF00
怎么办?我认为这将保持drawable主题因此保持边缘,但改变颜色。或者这是你已经尝试过的?