简体   繁体   中英

gradient color in integer-array android

i am using random color for my cardview background by integer-array in color.xml file

color.xml :

<item name="Gold" type="color">#FFFFD700</item>
<item name="Orange" type="color">#DSADSA</item>
<item name="LightSalmon" type="color">#EWQ5645W</item>

<integer-array name="androidcolors">
    <item>@color/Gold</item>
    <item>@color/Orange</item>
    <item>@color/LightSalmon</item>
</integer-array>

but i want gradient color for my backgrounds and i tried this:

<integer-array name="androidcolors">
    <item><gradient android:endColor="@color/blue" android:startColor="@color/darkblue" /></item>
</integer-array>

it doesn't work and i search any where and i think no body used this :| can you help me guys how to use gradient in integer-array or color.xml file ???

Create an xml file and place it in the Drawable folder. Use the following code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
    android:startColor="#8300bf"
    android:centerColor="#768087"
    android:endColor="#FF9000"
    android:angle="-90"
    android:type="linear"/>

Specify the startColor and endColor. In your LinearLayout, set the background by setBackground="@drawable/Your Gradient Filename" .

Try like this, 1. Create a drawable colors,For ex:

 card_drawable_bg.xml

    <?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
android:startColor="#ff9a6922"
android:centerColor="#ff9a4025"
android:endColor="#ff9a0e32"
android:angle="45"/>
        </shape>
    </item>
</selector>
  1. TypedArray is what you are looking for. I have samples using it. If you are interested, take a look at codes below:

First, integer-array in res/values/arrays.xml:

    <integer-array name="frag_home_ids">
    <item>@drawable/card_drawable_bg</item>

</integer-array>

Second, get resource integer values programmatically:

    TypedArray tArray = getResources().obtainTypedArray(
            R.array.frag_home_ids);
int count = tArray.length();
int[] ids = new int[count];
for (int i = 0; i < ids.length; i++) {
    ids[i] = tArray.getResourceId(i, 0);
}
//Recycles the TypedArray, to be re-used by a later caller. 
//After calling this function you must not ever touch the typed array again.
tArray.recycle();

Third, call the integer values like this:

holder.cardView.setCardBackgroundColor(ids[position]);

You can get integer values of string, color, integer, layout, menu...in this way.Hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM