溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spinner控件的列表項(xiàng)如何設(shè)置不同背景色

發(fā)布時(shí)間:2024-08-16 17:27:30 來(lái)源:億速云 閱讀:83 作者:小樊 欄目:移動(dòng)開(kāi)發(fā)

要為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è)置不同的背景色了。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI