Spinner控件的列表项如何设置不同背景色

发布时间:2024-08-16 17:27:30 作者:小樊
来源:亿速云 阅读:83

要为Spinner控件的列表项设置不同背景色,可以通过自定义ArrayAdapter来实现。首先创建一个自定义的ArrayAdapter类,然后在getView()方法中根据列表项的位置设置不同的背景色。

以下是一个示例代码:

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中使用这个自定义的ArrayAdapter来为Spinner设置不同的背景色:

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的列表项设置不同的背景色了。

推荐阅读:
  1. Android中Spinner如何使用
  2. Android中如何使用Spinner

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spinner

上一篇:Spinner在导航栏中的快速选择应用

下一篇:Spinner实现选项的拖拽排序与位置记忆

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》