From a list view in a fragment contained in a TabHost, I have implemented a CAB as well as highlighting of the longPressed (selected) row. This works perfectly running >= api 14. However, I am supporting api > 8.
In api 8 I am seeing strange behaviour whereby the wrong view is being highlighted in the list when longPressing a list item, sometimes. It seems that depending on how many rows are visible in the list determines whether or not the highlighting will work. This is very baffling because the method that performs the background color change is using the view that was passed in to it and the position parameter is indeed correct.
Is this a bug or am I missing something?
listView.setAdapter(
new myAdapter(
inflater,
tvSeason)
);
listView.setOnItemLongClickListener( new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
dismissActionMode();
return false;
}
// Start the CAB using the ActionMode.Callback defined above
mActionMode = getSherlockActivity().startActionMode(mActionModeCallback);
view.setSelected(true);
selectedTvEpisode = (TvEpisode)listView.getAdapter().getItem(position);
mActionMode.setTitle(MyApp.getResourceString(R.string.tv_episode_number, selectedTvEpisode.getNumber()));
view.setBackgroundColor(getActivity().getResources().getColor(R.color.lime));
selectedView = view;
return true;
}
});
Careful, do not set the views background color like that! Remember: the views in ListView
get recycled. What you should do is to get your data item, set a selected flag, and then call notifyDataSetChanged()
in the Adapter
. Set the background according to the selected flag in Adapter.getView()
.