Android:动态填充微调器然后更改其字体颜色

Android: Populate spinner dynamically then change its font color

我有一个数组,使用此方法

从 JSON 填充其项目
JSONObject dataProvinsi = new JSONObject(data.getString("data"));
ArrayList<CharSequence> arrKota = new ArrayList<>();
JSONArray jsArrKota = dataProvinsi.getJSONArray("kota");
if(jsArrKota.length() > 0) {
    for (int i = 0; i < jsArrKota.length(); i++) {
        arrKota.add(jsArrKota.get(i).toString());
    }
}

然后我的微调器从这些数组中填充它的项目。这是我填充微调项的代码

ProvinsiAdapter provinsiAdapter = new ProvinsiAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, arrKota);
spRujukanKota.setAdapter(provinsiAdapter);

我创建了自己的适配器class

public class ProvinsiAdapter extends ArrayAdapter<CharSequence> {
    private final Context context;
    private final ArrayList<CharSequence> itemsArrayList;

    public ProvinsiAdapter(Context context,int resource, ArrayList<CharSequence> itemsArrayList) {

        super(context, android.R.layout.simple_spinner_item, itemsArrayList);

        this.context = context;
        this.setDropDownViewResource(resource);
        this.itemsArrayList = itemsArrayList;
    }
}

我的微调器运行良好,但我遇到了一些问题。我的微调器文本变白,我无法将其颜色更改为黑色。我的问题是,如何更改微调器文本颜色?任何帮助,将不胜感激。谢谢。

因为您使用的是 id 调用的本机布局:"android.R.layout.simple_spinner_item" 系统将显示此布局及其规格。

那么你必须做什么?!

你有两个选择:

A- 打开此布局并查找 textView 的 ID,即 "R.id.text1" 然后覆盖自定义适配器中的 "getView()" 方法,并使用以下代码更改文本的颜色:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
    }
    TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
    textView.setTextColor(R.color.your_color);

    return convertView;
}

或者:B- 您可以按自己的方式工作(具有自定义布局的自定义适配器) 您也将以同样的方式覆盖 getView。

您可以查看此 link 以获得进一步的说明: how to change spinner text size and text color