4

我正在尝试使用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.access$800(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.access$800(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

我的主要活动:

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) {

    }
}

偏好片段:

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);
    }

}
4

2 回答 2

11

APreferenceFragment已经膨胀了适当的布局以供使用 - 通过使用您自己的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;
}
于 2015-09-20T17:43:38.090 回答
4

注释掉你的onCreateView()方法。

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

PreferenceFragment可能期望它根据您的堆栈跟踪onCreateView()创建缺少的内容。RecyclerView

于 2015-09-20T17:43:05.140 回答