4

私は楕円形を描くxmlを持っています、コードは以下の通りです:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#61118"/>
    <stroke android:width="1sp" android:color="#1B434D" />
</shape>

ここでandroid:color="#61118"、Java クラスから値を渡す必要があります。それは可能ですか?

そうでない場合、別の方法はありますか?

4

2 に答える 2

5

残念ながら、引数を XML Drawable に渡すことはできません。

異なる値があま​​りない場合は、 を使用して<level-list>、形状の異なるバージョンを提供できます。

次に、ドローアブルに関連付けられたレベルを変更して、 を使用して色を変更しますDrawable.setLevel(int)


my_drawable.xml

<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:maxLevel="0">
        <shape android:shape="oval">
            <solid android:color="@color/red"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="1">
        <shape android:shape="oval">
            <solid android:color="@color/green"/>
            <stroke android:width="1sp" android:color="@color/border" />
        </shape>
    </item>
    <item android:maxLevel="2">
        <shape android:shape="oval">
            <solid android:color="@color/blue"/>
            <stroke android:width="1sp" android:color="@color/blue" />
        </shape>
    </item>
</level-list>

MyActivity.java

// myView is a View (or a subclass of View) 
// with background set to R.drawable.my_drawable
myView.getBackground().setLevel(0); // Set color to red
myView.getBackground().setLevel(1); // Set color to green
myView.getBackground().setLevel(2); // Set color to blue

// myImageView is an ImageView with its source
// set to R.drawable.my_drawable
myImageView.setImageLevel(0); // Set color to red
myImageView.setImageLevel(1); // Set color to green
myImageView.setImageLevel(2); // Set color to blue
于 2013-03-21T17:33:25.060 に答える
1

はい、形状の色を動的に変更できます。XMLが「res/drawable/oval_shape.xml」にあると仮定します

GradientDrawable shape = (GradientDrawable) getResources().getDrawable(R.drawable.oval_shape);
int argb = 0x12345678;
shape.setBackground( argb );

枠の色を変更したい場合

int width = 1;
int argb = 0x87654321;
shape.setStroke( width, argb );

このソリューションでは、ビューを使用してレベルを設定する必要がないため、レベル リストを使用するよりも柔軟性が高くなります。

于 2013-11-21T01:25:22.297 に答える