ListFragment getListView()在屏幕旋转后返回null

时间:2013-11-03 17:00:17

标签: android android-layout listview android-listview android-listfragment

我在getListView()的{​​{1}}中致电OnActivityCreated()。它工作正常,但如果我旋转设备屏幕并再次调用getListView(),它将返回null。

这是ListFragment 代码:

ListFragment

这是布局xml( my_list_fragment.xml ):

public class MyListFragment extends ListFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.my_list_fragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ListView list = getListView();

        if (list != null) {
            //List is not null!
        }
        else {
            //List is null, there is an error.
        }
    }

}

2 个答案:

答案 0 :(得分:5)

我认为你应该在onViewCreated()中调用它:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ListView list = getListView();

    ...
}

答案 1 :(得分:1)

这是我的解决方案:

在我的 ListFragment 中,我像这样覆盖 onCreate 方法......

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setRetainInstance(true); // handle rotations gracefully

    ...
}

在我的 FragmentActivity 中,我在 onCreate 方法中为 FragmentManager 添加了一个标签,就像这样......

@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    ...

    // create or retrieve the venue list fragment
    final String venueListTag = VenueListFragment.class.getName();
    final FragmentManager fragmentManager = getSupportFragmentManager();
    VenueListFragment venueListFragment = (VenueListFragment) fragmentManager.findFragmentByTag(venueListTag);
    if (venueListFragment == null) {
        venueListFragment = new VenueListFragment();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.main, venueListFragment, venueListTag);
        fragmentTransaction.commit();
    }

    ...
}
如果您有兴趣,

here更多关于 setRetainInstance 。 我不确定Android团队是否对使用 setRetainInstance 感到不满,但他们肯定会保守秘密