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

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

我在 ListFragmentOnActivityCreated() 中调用了 getListView()。它工作正常,但如果我旋转设备屏幕并再次调用 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" />

最佳答案

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

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

    ...
}

关于android - 屏幕旋转后 ListFragment getListView() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755477/

相关文章:

android - 如何获得有效的误码率或接收质量

android - 编译语言res文件时出现AAPT错误

android - System.exit(0) 真的那么危险吗?

android - RippleDrawable 不在 View 上绘制

android - 布局问题 : SliderDrawer doesn't fill parent width

android - ListView 项目中的椭圆形 TextView 不起作用

android - 在 Android 上使用 Camera API 尽可能快地拍照

Android 支持多分辨率和多布局文件夹

java - 扩展 ListActivity android.R.id.list

.net - 有没有一种简单的方法可以通过 DataTable 填充 ListView?