1

我打电话给getListView()OnActivityCreated()ListFragment. 它工作正常,但如果我旋转设备屏幕并再次调用 getListView() 它返回 null。

这是 ListFragment代码:

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.
        }
    }

}

这是布局 xml ( my_list_fragment.xml ):

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
4

2 回答 2

4

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

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

    ...
}
于 2013-11-03T17:02:50.353 回答
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();
    }

    ...
}

如果您有兴趣,这里有更多关于setRetainInstance的信息。我不确定 android 团队是否对使用setRetainInstance 不满意,但他们确实保密

于 2014-04-05T13:28:45.977 回答