您好,登錄后才能下訂單哦!
要為Spinner控件的列表項(xiàng)設(shè)置不同背景色,可以通過(guò)自定義ArrayAdapter來(lái)實(shí)現(xiàn)。首先創(chuàng)建一個(gè)自定義的ArrayAdapter類,然后在getView()方法中根據(jù)列表項(xiàng)的位置設(shè)置不同的背景色。
以下是一個(gè)示例代碼:
public class CustomArrayAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> mItems;
private int[] mColors;
public CustomArrayAdapter(Context context, List<String> items, int[] colors) {
super(context, R.layout.spinner_item, items);
mContext = context;
mItems = items;
mColors = colors;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setBackgroundColor(mColors[position % mColors.length]);
return view;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
view.setBackgroundColor(mColors[position % mColors.length]);
return view;
}
}
然后在Activity中使用這個(gè)自定義的ArrayAdapter來(lái)為Spinner設(shè)置不同的背景色:
List<String> items = Arrays.asList("Item 1", "Item 2", "Item 3", "Item 4");
int[] colors = new int[]{Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW};
CustomArrayAdapter adapter = new CustomArrayAdapter(this, items, colors);
Spinner spinner = findViewById(R.id.spinner);
spinner.setAdapter(adapter);
這樣就可以為Spinner的列表項(xiàng)設(shè)置不同的背景色了。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。