setBackgroundColor改变颜色比按钮更多

时间:2015-06-21 07:47:21

标签: android android-button

我正在尝试将颜色设置为按钮,但是当我写下来时:

 button.setBackgroundColor(getResources().getColor(R.color.white));

按钮变成白色,但周围也有一些空间(linearLayout中有几个按钮,所以它看起来像一个大的白色按钮。)

任何人都知道如何解决这个问题?

更新:我的XML:

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:weightSum="2"
        android:layout_weight="1"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:background="@android:color/white"
            android:id="@+id/button1"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/button2"                
            />


    </LinearLayout>

这里左边的按钮看起来比右边的要大,因为我改变了它的颜色

5 个答案:

答案 0 :(得分:2)

您不需要在活动中编写该代码

只是在您的XML中:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:background="#ffffff"
        android:id="@+id/button1"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"                
        />

访问此网站获取颜色代码:

http://color-hex.com

答案 1 :(得分:2)

这是因为按钮的默认实现使用自定义drawable作为背景,更改背景将覆盖它并丢失所有样式。

相反,您要做的是使用颜色覆盖现有的背景可绘制:

button.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);

您还可以找到该按钮使用的默认样式,复制它并更改那里的颜色,但这样做会更有效。

答案 2 :(得分:1)

如果使用背景颜色,请将按钮的高度和宽度设置为特定尺寸,以免包装内容。

答案 3 :(得分:0)

你试过吗

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center"
    android:weightSum="2"

    >
    <Button
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:background="@android:color/white"
        android:id="@+id/button1"
        />
    <Button
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button2"                
        />


</LinearLayout>

在您的parrent布局(LinearLayout)中,您设置weightSum为2,但在子元素中使用android:layout_weight="1"不会为孩子做出贡献

答案 4 :(得分:0)

您可以尝试 Xamarin

button.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#f00ece"), Android.Graphics.PorterDuff.Mode.Multiply);