我想在屏幕旋转后以编程方式(重新)突出显示选定的列表项。
public class MyListFragment extends ListFragment {
private static final String tag = MyListFragment.class.getName();
private static final String indexTag = "index";
private int index = -1;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
if (savedInstanceState != null) {
index = savedInstanceState.getInt(indexTag, -1);
Log.d(tag, "Restored index " + index + " from saved instance state.");
}
}
@Override
public void onResume() {
super.onResume();
if (index >= 0) {
showDetails(index);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
private void showDetails(int index) {
this.index = index;
getListView().setItemChecked(index, true);
// update details panel
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(indexTag, index);
}
}
我在自定义适配器中使用 CheckedTextView 作为项目视图:
public class MyListAdapter extends BaseAdapter {
private static final String tag = MyListAdapter.class.getName();
@Override
public CheckedTextView getView(int position, View convertView, ViewGroup parent) {
if (convertView == null || !(convertView instanceof CheckedTextView)) {
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.simple_list_item_single_choice, parent, false);
}
((CheckedTextView)convertView).setText("test");
return (CheckedTextView)convertView;
}
}
在调用屏幕旋转showDetails()
并且详细信息面板更新但setItemChecked()
不执行任何操作并且该项目仍未突出显示之后。我还注意到,当setItemChecked()
不需要通过触摸事件单击它的项目时,该行无论如何都会突出显示。
那么如何在 onResume 阶段以编程方式检查项目?