如何更改微调项的背景颜色

How to change background color of spinner items

我正在使用 this 微调器库。我想更改微调器列表中已选择项目的颜色。我该怎么做?这就是我填充微调器点击数据的方式:

spinner1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Cursor crs = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_ZONE +" WHERE "+ ItemsTable.COLUMN_ZONE_ID +"<>"+ zone_id1
                            +" AND "+ ItemsTable.COLUMN_ZONE_ID +"<>"+ zone_id2 +" AND "+ ItemsTable.COLUMN_ZONE_ID +"<>"+ zone_id3 +"", null);
                    Integer[crs.getCount()];
                    List<Zone> listOfZones = new ArrayList<Zone>();

                    while(crs.moveToNext())
                    {
                        String title = crs.getString(crs.getColumnIndex("title"));
                        Integer title_id = crs.getInt(crs.getColumnIndex("id"));

                        listOfZones.add(new Zone(title_id, title));

                    }
                    crs.close();

                    ArrayAdapter<Zone> zoneadapter = new ArrayAdapter<Zone>(getActivity(),
                            android.R.layout.simple_dropdown_item_1line, listOfZones);
                    spinner1.setAdapter(zoneadapter);
                }
                return false;
            }
        });

在上面的代码中,我从列表中删除了已选中的项目,但我想更改已选中项目的背景颜色。

您可以通过为 spinner layout 创建 xml 文件来提供背景颜色。按照以下步骤操作。

1) 您需要在 layout 文件夹下创建一个 xml 文件。

2) 创建布局,其中包括一个显示项目名称的 TextView

3) 为主 rootview 布局提供背景颜色。例如 android:background="@color/anycolor".

并在微调器适配器中绑定此布局。

这是自定义适配器:

public class CustomAdapter extends BaseAdapter {
Context context;
List<Zone> listOfZones;
LayoutInflater inflter;

public CustomAdapter(Context applicationContext,  List<Zone> listOfZones) {
    this.context = applicationContext;
    this.listOfZones = listOfZones;
    inflter = (LayoutInflater.from(applicationContext));
}

@Override
public int getCount() {
    return flags.length;
}

@Override
public Object getItem(int i) {
    return null;
}

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

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    view = inflter.inflate(R.layout.your_layout_name, null);
    TextView names = (TextView) view.findViewById(R.id.textView);
    names.setText(listOfZones.get(i).yourObjectName);
    return view;
}}

然后像这样将其绑定到微调器:

 CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),listOfZones);
 your_spinner.setAdapter(customAdapter);