希望是一个快速的问题。我将如何在 ListFragment 上设置默认选择。我希望该 Activity 在已选择顶部列表项的情况下启动。谢谢
最佳答案
摘自 Android 文档 ( http://developer.android.com/guide/components/fragments.html#Example ) 和支持库 API 演示中的官方示例:
该示例中的 ListFragment 使用 getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
和 getListView().setItemChecked(index, true);
在 ListFragment 的 onActivityCreated
中使列表项被选中/突出显示的方法,其中 index
取自默认设置为 0 的局部变量。所以你会有类似的东西:
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
// (Replace this with your own list adapter stuff
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
// ... the rest of the ListFragment code ....
}
看看我在顶部链接到的那个例子,它应该能让你开始运行!
关于android - ListFragment 设置初始选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410612/