5

私はボタンを 2 つ持っています。形は同じで、色だけが異なります

b1.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#ff0000"/>
</shape>

b2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp" />
    <stroke android:width="5px" android:color="#000000" />
    <solid
        android:color="#00ff00"/>
</shape>

レイアウト.xml

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b1"
    android:text="B1" />


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/b2"
    android:text="B2" />

異なる色のボタンを 100 個作成したい場合は、100 個の描画可能な xml を作成する必要があります。

描画可能な xml を 1 つだけ作成して、レイアウト xml の色やその他の属性を上書きすることはできますか?

4

1 に答える 1

4

XML 経由ではできません。動的な処理が必要な場合、XML は固定要素です。Java を使用してください。

特定のケースでは、次のような Drawable ペイントと ColorFilter を使用して、必要なものを達成しようとすることができます。

Button b1 = (Button) findViewById(R.id.button1);
ShapeDrawable sd = (ShapeDrawable) b1.getBackground();
sb.getPaint().setColor(color);
sb.setColorFilter(... something);
于 2015-07-08T08:25:23.880 に答える