尝试使用自定义适配器,这也可以帮助您完全控制您的项目并设置选择的默认项目;listView XML 和 item XML 没有特殊设置。使用 getViewTypeCount() 和 selectedViewType 是避免回收视图的关键。
public class ListAdapter extends ArrayAdapter<MyObj> {
private final int layoutInflater;
private Context context;
private List<MyObj> items;
private int mSelectedItem = 0;
private int TAG_UNSELECTED = 0;
private int TAG_SELECTED = 1;
public ListAdapter(Context context, int resource, List<MyObj> items) {
super(context, resource, items);
this.context = context;
this.layoutInflater = resource;
this.items = items;
}
public void selectItem(int position) {
mSelectedItem = position;
notifyDataSetChanged();
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return position == mSelectedItem ? TAG_SELECTED : TAG_UNSELECTED;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(layoutInflater, null);
}
MyObj myObj = items.get(position);
TextView textView = (TextView) v.findViewById(R.id.title);
textView.setText(myObj.title);
int type = getItemViewType(position);
if(type == TAG_SELECTED) {
v.setBackgroundColor(Color.parseColor("#1da7ff"));
textView.setTextColor(Color.parseColor("#ffffff"));
} else {
v.setBackgroundColor(Color.parseColor("#f8f8f8"));
textView.setTextColor(Color.parseColor("#474747"));
}
return v;
}
}
然后在您的活动中:
ListView listView = (ListView) findViewById(R.id.list_view);
ListAdapter adapter = new ListAdapter(mContext, R.layout.item_layout, list);
listView.setAdapter(adapter);
adapter.selectItem(0); // Default selected item
// Get selected item and update its background
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
adapter.selectItem(position);
}
});