I want my ListView to highlight the selected item until selection changes. Also, I want to be notified when selection changes.
In order to accomplish the first task, I call list.setChoiceMode(ListView.CHOICE_MODE_SINGLE).
I’m not sure how to accomplish the second. When a list item is clicked, my OnItemSelectedListener is never notified, and the OnItemClickListener is insufficient because by the time the OnItemClick event occurs, my ListView’s checkedItem has been modified, so I cannot distinguish if the click event resulted in a selection change (it is possible/likely that the clicked item was already selected).
One option would be to store the currently checked index in a member variable, which I could use to determine if the click event corresponds to a selection change. But this ugly and
So, for this choice mode, certainly there is a way to do this with the provided listeners?
public class Temp extends Activity implements OnItemClickListener, OnItemSelectedListener
{
ListView mView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
List<String> strings = new ArrayList<String>();
strings.add("1");
strings.add("2");
strings.add("3");
strings.add("4");
strings.add("5");
mView = new ListView(this);
mView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, strings));
mView.setItemChecked(0, true);
mView.setOnItemClickListener(this);
mView.setOnItemSelectedListener(this);
setContentView(mView);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//this never gets called
Log.e("item selected", ""+position);
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
Log.e("nothing seleted", "");
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//by the time this occurs, position == mView.getCheckedItemPosition()
Log.e("item clicked", ""+position);
}
}
The OnItemSelectedListener is only called by a ListView when you use a trackball, keyboard navigation, or use another type of non-touch navigation. It does not correlate to the choice mode.
This is the best option. It only involves one extra
intand an if-statement.