我有一个 ListView
,当用户单击其中一个项目时,我希望该项目变为蓝色。为此,我在 ListView
Activity 的 onCreate()
方法中为用户点击设置了一个监听器。
m_listFile=(ListView)findViewById(R.id.ListView01);
m_listFile.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);
}
});
对于第一个可见的项目,一切正常,但是当我滚动列表时,我有一个
arg0.getChildAt(arg2).setBackgroundColor(...)
处的 NullPointerException
,即使 arg2
值具有正确的项目索引位置。
我的ListView
有一个两行项目结构,当我加载ListView
时我使用这个适配器:
SimpleAdapter sa = new SimpleAdapter(
getApplicationContext(),
expsList,
R.layout.listelement,
new String[] { "screen_name","text" },
new int[] { R.id.Name, R.id.Value}) {
};
m_listFile.setAdapter(sa);
我不明白如何解决这个问题。我可以获得帮助吗?
最佳答案
您可以像这样扩展SimpleAdapter
:
private class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
v.setBackgroundColor(Color.BLACK); //or whatever is your default color
//if the position exists in that list the you must set the background to BLUE
if(pos!=null){
if (pos.contains(position)) {
v.setBackgroundColor(Color.BLUE);
}
}
return v;
}
}
然后在您的 Activity 中添加一个如下所示的字段:
//this will hold the cliked position of the ListView
ArrayList<Integer> pos = new ArrayList<Integer>();
并设置适配器:
sa = new MyAdapter(
getApplicationContext(),
expsList,
R.layout.listelement,
new String[] { "screen_name","text" },
new int[] { R.id.Name, R.id.Value}) {
};
m_listFile.setAdapter(sa);
当您单击该行时:
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// check before we add the position to the list of clicked positions if it isn't already set
if (!pos.contains(position)) {
pos.add(position); //add the position of the clicked row
}
sa.notifyDataSetChanged(); //notify the adapter of the change
}
关于android - ListView的item背景色设置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9757756/