我有这种静态方法来着色Spinner条目的背景,但它不起作用。有什么想法吗?如果不延长SpinnerAdapter
,你会怎么做?
public static void colorizeSpinnerElements(final Activity activity, final int id) {
final Spinner aux = (Spinner) activity.findViewById(id);
final SpinnerAdapter adapter = aux.getAdapter();
if (adapter != null) {
final int num = adapter.getCount();
for(int i = 0; i < num; i++) {
adapter.getView(i, null, null).setBackgroundColor(ColorHelper.COLOR_LIST[i]);
}
}
}
我认为这可能与我在加载Spinner
时只执行此操作有关,因此在调用getView()
来刷新显示时会丢失背景颜色。
答案 0 :(得分:1)
我认为你需要从适配器的getView()方法做同样的事情:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(ColorHelper.COLOR_LIST[position]);
return v;
}
修改强>
您可以override
使用getDropDownView
方法。为每个项目调用此方法。
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// expand your list item here
view = vi.inflate(R.layout.mylistitem, null);
}
// get whatever items are in your view
TextView text = (TextView) view.findViewById(R.id.text);
ImageView left = (ImageView) view.findViewById(R.id.leftImage);
// do whatever you want with your item view
view.setBackgroundColor(ColorHelper.COLOR_LIST[position]);
return(view);
}