简体   繁体   中英

Change spinner background color for specific item

I have a question . Is it possible to set a specific background color for specific item? . For example i would like to set "yellow" for item "DLUGOSC". Below is my strings.xml and spinner layout. Thanks

**strings.xml**
<resources>
<string name="app_name">Konwerter Jednostek</string>
<string name="action_settings">Settings</string>

<string-array name="units">
    <item><b>DLUGOSC</b></item>
    <item>Cal</item>
    <item>Centymetr</item>
    <item>Stopa</item>
    <item>Jard</item>
    <item>Metr</item>
    <item>Mila</item>
    <item>Kilometr</item>
    <item>Decymetr</item>
    <item>Milimetr</item>

</string-array>

Spinner layout

<Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spinner_from"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        />

Yes it is possible. Here I am highlighting "Cal".

List<String> units =   Arrays.asList(getResources().getStringArray(R.array.units));
    Spinner spinner = (Spinner) findViewById(R.id.spinner_from);
    spinner.setAdapter(new TestAdapter(units , this);



public class TestAdapter extends BaseAdapter {

List<String> strings;
Context context;

public TestAdapter(List<String> stringList, Context context) {
    strings = stringList;
    this.context = context;
}


@Override
public int getCount() {
    return strings.size();
}

@Override
public String getItem(int position) {
    return strings.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView textView = new TextView(context);

    textView.setText(strings.get(position));

    //here you can use position or string
    if(position == 1 || strings.get(position).equals("Cal")) {
        textView.setBackgroundColor(Color.RED);
    }

    return textView;
}

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