【发布时间】:2017-03-08 11:10:51
【问题描述】:
我有一个 ListView 并且我已对其进行了修改,因此当您按下列表项时,列表项背景颜色会发生变化,并且列表焦点位于该项目的中心。一切都按预期工作,没有问题。
但是,如果您滚动列表,您会发现另一个列表项的背景发生了变化,然后又一个又一个循环地发生变化。据我了解,ListView 中的项目正在被回收,这就是发生这种情况的原因。
例如,我的列表包含 12 个可以在屏幕上显示的项目,然后您需要滚动。如果您选择第一项,那么当您在实际设备上滚动列表时,第 15 个元素的背景也会发生变化。
有谁知道如何解决这个问题,例如只改变一个项目的背景,而不是这种重复模式的其他“选定项目”?
这是它的代码:
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
//this deselects the previously selected item (changes its background to the default one)
if(listItemPosition!=null) {
previouslySelected = vehicleListArrayAdapter.getView(listItemPosition,previousView,parent);
previouslySelected.setBackgroundColor(getResources().getColor(R.color.applicationBackground));
}
//verify if the pressed item has been set as itemPosition and if not, set it
if (listItemPosition == null || listItemPosition != position){
listItemPosition = position;
previousView = vehicleListArrayAdapter.getView(position,view,parent);
}
//set the selection to the listItemPosition (if we subtract 5, we set the focus on the center of the ListView)
realTimeVehicleListView.setSelection(listItemPosition-5);
//focus the list on that item
realTimeVehicleListView.requestFocus();
//change the background color of the selected item to emphasize it
currentlySelectedListItem = vehicleListArrayAdapter.getView(listItemPosition,view,parent);
currentlySelectedListItem.setBackgroundColor(getResources().getColor(R.color.selectedItem));
这是一些尝试使用标志的代码:
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
vehicleListItemSelected = true;
//this deselects the previously selected item (changes its background to the default one)
if(listItemPosition!=null) {
previouslySelected = vehicleListArrayAdapter.getView(listItemPosition,previousView,parent);
previouslySelected.setBackgroundColor(getResources().getColor(R.color.applicationBackground));
}
//verify if the pressed item has been set as itemPosition and if not, set it
if (listItemPosition == null || listItemPosition != position){
listItemPosition = position;
previousView = vehicleListArrayAdapter.getView(position,view,parent);
}
//set the selection to the listItemPosition (if we subtract 5, we set the focus on the center of the ListView)
realTimeVehicleListView.setSelection(listItemPosition-5);
//focus the list on that item
realTimeVehicleListView.requestFocus();
//change the background color of the selected item to emphasize it
if (vehicleListItemSelected){
currentlySelectedListItem = vehicleListArrayAdapter.getView(listItemPosition,view,parent);
currentlySelectedListItem.setBackgroundColor(getResources().getColor(R.color.selectedItem));
vehicleListArrayAdapter.notifyDataSetChanged();
vehicleListItemSelected = false;
}
编辑:这比我最初想象的还要糟糕。如果您选择第一个项目,它的背景会改变,然后您随机滚动列表并返回到第一个项目,它不再被选中。相反,选择了其他一些项目,可能是第二个或第三个项目,它的背景发生了变化,而不是您实际选择的第一个。
【问题讨论】: