我希望在屏幕旋转后以编程方式(重新)突出显示所选列表项。
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阶段以编程方式检查项目?
答案 0 :(得分:1)
在你的onActivityCreate()中加上showIndex(index),因为在屏幕上旋转Android会破坏当前活动并通过Bundle savedInstanceState创建另一个保存当前状态
答案 1 :(得分:0)
我解决了这个问题。我忘了我在活动中通过AsyncTask
设置列表适配器,所以当在onResume阶段调用showDetails()
时,我的片段仍然有空列表。
所以我从我的片段中移除了onResume
方法,将showDetails()
设为公开,并在设置适配器后从我的活动中调用它:
public void onListLoadDone(...) {
final MyListAdapter adapter = new MyListAdapter(...);
myListFragment.setListAdapter(adapter);
myListFragment.showDetails();
}