setBackgroundColor改变多个按钮的颜色。

问题描述 投票:3回答:5

我想给一个按钮设置颜色,但是当我写下:

 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>

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

android android-button
5个回答
3
投票

这是因为按钮的默认实现使用了自定义的drawable作为背景,改变背景会覆盖它,失去所有的样式。

相反,你要做的是用颜色覆盖现有的背景可绘制。

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

你也可以找到按钮使用的默认样式,复制它,然后在那里改变颜色,但那会更麻烦。


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
投票

将按钮的高度和宽度设置为特定的大小,如果你使用背景色,则不会包裹内容。


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" 稚气未脱


0
投票

你可以试试在 Xamarin

button.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#f00ece"), Android.Graphics.PorterDuff.Mode.Multiply);
© www.soinside.com 2019 - 2024. All rights reserved.