Android开发修改Spinner选中以后列表字体的颜色

xiaoxiao2021-02-28  48

    遇到这样一个需求,找了很久只找到能修改初始文字的颜色,不能改列表中的颜色。最后解决的实现方法是新写一个adapter去继承ArrayAdapter,在使用这个adapter的时候,传入点击的位置,然后在adapter里改变颜色。

以下为自定义的adapter:

import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class TestArrayAdapter extends ArrayAdapter<String> { private Context mContext; private String [] mStringArray; private int type; public TestArrayAdapter(Context context, String[] stringArray) { super(context, android.R.layout.simple_spinner_item, stringArray); mContext = context; mStringArray=stringArray; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { //修改Spinner展开后的字体颜色 if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent,false); } //此处text1Spinner默认的用来显示文字的TextView TextView tv = (TextView) convertView.findViewById(android.R.id.text1); tv.setText(mStringArray[position]); tv.setTextSize(20f); tv.setTextColor(Color.BLACK); //根据点击位置改变颜色 if(position == type){ tv.setTextColor(Color.RED); } return convertView; } @Override public View getView(int position, View convertView, ViewGroup parent) { // 修改Spinner选择后结果的字体颜色 if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false); } return convertView; } public void setType(int type) { this.type = type; } }

以下为mainActivity里的使用:

spinner = (Spinner) view.findViewById(R.id.spinner);

private String[] sortList = new String[]{"呀哈哈1","呀哈哈2","呀哈哈3","呀哈哈4","呀哈哈5"}; TestArrayAdapter arrayAdapter = new TestArrayAdapter(getActivity(),sortList); spinner.setAdapter(arrayAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { //此处设置选中后的TextView属性 TextView tv = (TextView) view; tv.setTextColor(getResources().getColor(R.color.black)); //将点击的序号传入adapter                    arrayAdapter.setType(i); //点击后要使用的方法

                   fun(i); 

          } 

          @Override public void onNothingSelected(AdapterView<?> adapterView) {

          }

});

转载请注明原文地址: https://www.6miu.com/read-2300326.html

最新回复(0)