android 支持 v14 PreferenceFragment 崩溃

android support v14 PreferenceFragment crashes

我正在尝试使用 android.support.v14.preference 库中的 PreferenceFragment 在 Android 应用程序中显示设置。但是,当我尝试打开首选项时,应用程序崩溃并出现奇怪的 NullPointerException。如果我在 PreferenceFragment 中省略对 addPreferenceFromResource(R.xml.preferences) 的调用,则不会发生这种情况,但当然不会显示偏好。

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hardboard.preferencetest/com.hardboard.preferencetest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
            at android.app.ActivityThread.access0(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5373)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
            at android.support.v14.preference.PreferenceFragment.bindPreferences(PreferenceFragment.java:473)
            at android.support.v14.preference.PreferenceFragment.onActivityCreated(PreferenceFragment.java:278)
            at android.app.Fragment.performActivityCreated(Fragment.java:2061)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:912)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
            at android.app.BackStackRecord.run(BackStackRecord.java:834)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
            at android.app.Activity.performStart(Activity.java:6005)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2342)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
            at android.app.ActivityThread.access0(ActivityThread.java:156)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5373)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

我读到 support-v14 PreferenceFragment 在内部使用 RecyclerView 来显示首选项列表,但我做错了什么导致 RecyclerView 成为 null

我的主要Activity:

public class MainActivity extends AppCompatActivity implements SettingsFragment.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .addToBackStack(null)
                .commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

PreferenceFragment:

public class SettingsFragment extends android.support.v14.preference.PreferenceFragment {

    private OnFragmentInteractionListener mListener;

    public SettingsFragment() {
        // Required empty public constructor
    }

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

    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.preferences);
    }

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

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mListener = (OnFragmentInteractionListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

}

注释掉您的 onCreateView() 方法。

或者,链接到 onCreateView() 的超类实现并将其响应嵌入到您自己的包装器中,如果出于某种原因您想要在股票 PreferenceFragment UI 周围添加其他内容。

PreferenceFragment 可能期望它的 onCreateView() 创建每个堆栈跟踪缺少的 RecyclerView

PreferenceFragment 已经膨胀了适当的布局以供使用 - 通过使用您自己的 R.layout.fragment_settings,它无法找到它需要的适当视图。

如果您想修改 RecyclerView 本身,请考虑覆盖 onCreateRecyclerView()。相反,如果您想围绕默认布局创建一些自定义框架,您可以使用如下模式:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_settings, container, false);
    // The frame you want to embed the parent layout in.
    final ViewGroup innerContainer = (ViewGroup) view.findViewById(R.id.main_frame);
    final View innerView = super.onCreateView(inflater, innerContainer, savedInstanceState);
    if (innerView != null) {
        innerContainer.addView(innerView);
    }
    return view;
}