【发布时间】:2015-03-19 14:15:49
【问题描述】:
选择项目后,我需要在列表视图中突出显示所选行。
例如:我选择第一个项目,它会突出显示,如果我选择第三个项目,然后删除第一个突出显示的项目,然后突出显示第三个项目。
我在 Stackoverflow 上看到过很多示例和问题,但还没有找到合适的解决方案。
下面是我的代码,它可以工作,但我需要选择两次才能突出显示,我该如何修改它才能顺利工作?
ListView mainListView = (ListView) findViewById( R.id.mainListView );
// Create and populate a List of planet names.
planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune",
"Ceres","Pluto","Haumea","Makemake","Eris"};
planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
planetsAdapter = new PlanetsAdapter (this,planetList);
planetsAdapter .setNotifyOnChange(true);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter(planetsAdapter );
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
planetsAdapter.setSelectedPosition(position);
planetsAdapter.notifyDataSetChanged();
}
});
改编类:
public class PlanetsAdapter extends ArrayAdapter<String> {
private ArrayList<String> planets;
private Context mContext = null;
private LayoutInflater inflater;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public PlanetsAdapter (Context context,ArrayList<String> objects) {
super(context,0,objects);
mContext = context;
planets = objects;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
}
public int getSelectedPosition(){
return selectedPos;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, null);
}
TextView title = (TextView) convertView
.findViewById(R.id.rowTextView);
// change the row color based on selected state
if(position == selectedPos){
//title.setTextColor(Color.parseColor("#FFFFFF"));
title.setBackgroundColor(Color.parseColor("#ED07E1"));
}else{
//title.setTextColor(Color.parseColor("#000000"));
title.setBackgroundColor(Color.parseColor("#e2e2e2"));
}
title.setText(getItem(position));
return convertView;
}
}
编辑:在下面回答
For anyone who is looking for answers, i have answered it below hope it helps.
【问题讨论】:
-
尝试在您的适配器中将
notifyDataSetChanged();添加到setSelectedPosition -
@MD 之前尝试过,但我仍然需要选择该项目两次才能突出显示。
-
你的问题对我来说并不难理解。
select the item twice to get highlighted. -
@MD 我显示的代码突出显示了行或项目,但第一次它不会突出显示,再次选择相同的项目时它会突出显示。
-
@user2056563 您是否将活动扩展到 ListActivity?
标签: android listview adapter highlight listviewitem