Listview
从android中的其他活动返回时,如何选择项目颜色保持不变?
请给我一个适当的解决方案。在这里,我附上了Adapter
课
public class SelectedAdapter extends ArrayAdapter {
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private int selitem;
public SelectedAdapter(Context context, int textViewResourceId, List objects) {
super(context, textViewResourceId, objects);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.simplerow, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.rowTextView);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
//label.setBackgroundResource(R.color.blue2);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
/*
// to use something other than .toString()
MyClass myobj = (MyClass)this.getItem(position);
label.setText(myobj.myReturnsString());
*/
return(v);
}
}
主要活动类
final Context context = this;
protected ListView applv ;
private ArrayAdapter<String> listAdapter ;
private SelectedAdapter selectedAdapter;
private ArrayList list;
list = new ArrayList();
list.add("Actuator");
list.add("Agitator - Liquid");
list.add("Agitator - Slurry");
list.add("Air Separator");
list.add("Belt Plow");
list.add("Blower");
applv = (ListView) findViewById( R.id.lvapps);
applv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
selectedAdapter = new SelectedAdapter(this,0,list);
selectedAdapter.setNotifyOnChange(true);
applv.setAdapter( selectedAdapter );
applv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
itemsel = applv.getAdapter().getItemViewType(position);
// TODO Auto-generated method stub
item = applv.getAdapter().getItem(position).toString();
selectedAdapter.setSelectedPosition(position);
}
});