这是我的代码。这里所选行的背景颜色正在变化。但滚动后,未选择视图的bachground颜色也会改变。我想防止这个问题。有什么帮助吗?
public class ListDemoActivity extends ListActivity {
String[] names = {
"Dwight",
"Kennedy",
"Johnson",
"Richard",
"Gerald",
"Jimmy",
"Ronald",
"George",
"Bill",
"B. Bush",
"Rana"
};
View view;
int posn = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, names));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("Log", "Clicked posn"+position);
Log.i("Log", "id is: "+id);
if(posn == -1)
{
v.setBackgroundResource(R.color.blue);
// l.getChildAt(position).setBackgroundResource(R.color.blue);
view = v;
posn = position;
}
else if (posn == position)
{
v.setBackgroundResource(R.color.blue);
//l.getChildAt(position).setBackgroundResource(R.color.blue);
}
else
{
Log.i("Log", "Count of child: "+l.getChildCount());
// View view = l.getChildAt(posn);
// Log.i("Log", "Position: "+view.)
//view.setBackgroundResource(R.color.black);
//view = l.getChildAt(position);
//view.setBackgroundResource(R.color.blue);
view.setBackgroundResource(R.color.black);
v.setBackgroundResource(R.color.blue);
view = v;
posn = position;
}
}
}
答案 0 :(得分:1)
这是因为ListView通过其适配器重用其单元格;当一个单元格滚动到视图外时,它会被放在底部,所以如果你将它变成蓝色并滚动它,它将显示在下面。
您可以编写一个简单的自定义适配器,在其中跟踪您想要着色的单元格,并在您必须覆盖的getView(..)
方法中相应地着色。另请参阅ListViews上的this video。