0

我有这个静态方法来为 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()调用刷新显示时它会丢失背景颜色。

4

1 回答 1

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;    
}

编辑:

你可以overridegetDropDownView方法。为每个项目调用此方法。

@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);
}
于 2013-01-16T09:42:26.217 回答