2014-12-02 126 views
0

我在显示活动之前更改了一些按钮背景颜色,并且当显示按钮时,它们缺失了它们周围的空白区域。更改按钮背景颜色可移除空白区域

enter image description here

如何获得的按钮是红色的,其中灰色,并保持白色空间?

+0

检查我编辑的答案。 – Carnal 2014-12-03 10:11:32

回答

0

创建drawable一个red_button.xml这样的:

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" > 
<stroke android:width="2dp" 
     android:color="#80FFFFFF" /> 

    <corners android:radius="25dp" /> 

    <gradient android:angle="270" 
      android:centerColor="#ff0000" 
      android:endColor="#ff0000" 
      android:startColor="#ff0000" /> 
</shape> 

要获得相同的形状作为默认Button

可以玩弄radiusstroke widthstroke color让你Button你想要的。

编辑:您可以将颜色添加到原来的默认Button这样的:

Drawable d = yourButton.getBackground(); 
PorterDuffColorFilter filter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); // or whatever color you like 
d.setColorFilter(filter); 
+0

我可以通过代码执行此操作吗,而不是将它放入XML中? – 2014-12-02 15:39:54

+0

为什么你想在代码中做到这一点?创建XML,只需在button.setBackgroundResource(R.drawable.red_button)中添加背景代码; – Carnal 2014-12-02 15:41:51

+0

我想通过代码来做到这一点,因为我通过代码设置背景颜色。如果我制作了一个通用的按钮布局,并将其设置为setBackgroundResource(),我可以使用代码更改其背景颜色吗?所以我不需要为每种颜色需要一个布局? – 2014-12-02 16:38:52

0

你可能已经错过了布局设置保证金。实际上,按钮周围有一个空白区域,所有按钮都会被触摸,所以当您设置背景时,空白区域也会变成红色。我猜这应该没问题。

布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 

    <Button 
     android:id="@+id/one" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="About" 
     android:layout_margin="5dp" /> 

    <Button 
     android:id="@+id/two" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Gallery" 
     android:layout_margin="5dp"/> 

    <Button 
     android:id="@+id/third" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Media" 
     android:layout_margin="5dp"/> 

</LinearLayout> 

在strings.xml中

<color name="red">#FF0000</color> 

在Java

one = (Button) findViewById(R.id.one); 
     two = (Button) findViewById(R.id.two); 
     three = (Button) findViewById(R.id.third); 
     one.setBackgroundResource(R.color.red); 
     two.setBackgroundResource(R.color.red); 
     three.setBackgroundResource(R.color.red); 

输出

This is your desired output?