【问题标题】:Same shape with different colors in AndroidAndroid中相同的形状不同的颜色
【发布时间】:2015-10-14 04:07:07
【问题描述】:

我有以下 xml 文件。我想用一些背景制作按钮圆形的形状 颜色。但我的每个按钮将包含不同的背景颜色。对于一个按钮,我可以通过采取 xml中的drawable并定义button的形状和颜色。但是通过这种方法我需要创建 形状和颜色的每个按钮的单独 xml 文件。但我只想在一个包含形状和不同颜色的 xml 文件中执行此操作,以便我可以减少可绘制的 xml 文件

<?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="match_parent"
                    android:orientation="vertical" >

        <Button android:id="@+id/button"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                     />
        <Button android:id="@+id/button1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                     />
        <Button android:id="@+id/button2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                     />
        </LinearLayout>

【问题讨论】:

  • 为什么不以编程方式更改颜色或背景?
  • @SyedNazarMuhammad 是的,这可能是解决我的问题的一种选择,但它会增加我的代码,我希望尽可能减少代码
  • 那怎么会呢?
  • @SyedNazarMuhammad 我可以用一个 xml 文件来做吗
  • @SyedNazarMuhammad 如果我不能,请告诉我如何以编程方式设置按钮的颜色和背景

标签: android xml android-drawable


【解决方案1】:

定义形状roundbutton.xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring">
        <solid android:color="#FFFFFF"/>

    </shape>

然后将形状分配给您的按钮

 <Button
            android:id="@+id/round1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/roundbutton"
            android:gravity="center" />

之后你可以使用java来改变颜色

 round1.setBackgroundColor(Color.BLACK);

你需要import android.graphics.Color;而不是:import android.R.color;

或十六进制代码(不是 3 字节)0xFF000000,其中第一个字节设置 alpha。

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多