0

在 Android 应用程序中,我想更改Button.

我尝试将“背景”属性从更改为android:Drawable/btn_default_holo_light#FFFF00并根据需要获得了新颜色。缺点是形状也发生了Button变化:原来Button的边缘消失了,彩色区域变得越来越宽,完全填满了它的区域。

如何仅更改背景颜色而不更改Button' 的外观?

4

3 回答 3

4

您可以以编程方式设置按钮背景

b= (Button) findViewById(R.id.button1);
b.setBackgroundColor(Color.RED);  

使用自定义可绘制对象设置背景。

可绘制文件夹中的 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>

按下的.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" />
于 2013-04-15T17:32:42.897 回答
0

您不能像那样更改背景颜色,因为 Button 形状是在其背景图像中定义的。如果您想要不同的颜色,则需要创建自己的背景。只需谷歌搜索“android 自定义按钮”,您就会发现大量信息和教程。

于 2013-04-15T17:31:16.617 回答
0

android:backgroud=#FFFF00在按钮标签内怎么样。我认为这会保留可绘制主题,因此会保留边距,但会更改颜色。或者这是你已经尝试过的?

于 2013-04-15T17:31:39.397 回答