首页 > 解决方案 > 片段上下文中的错误(oncreatedialog)

问题描述

我有一个扩展 BottomSheetDialogFragment 的片段。运行应用程序时出现此错误。我这个问题出在:mContext = getActivity().getApplicationContext();我试图用它替换它,mContext = getActivity();但它再次显示错误。

这是错误: 在此处输入图像描述

这是代码:

public class FragmentBottomSheetDialogFull extends BottomSheetDialogFragment {
 @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        final View view = View.inflate(getContext(), R.layout.aa, null);

        dialog.setContentView(view);
        mBehavior = BottomSheetBehavior.from((View) view.getParent());
        mBehavior.setPeekHeight(BottomSheetBehavior.PEEK_HEIGHT_AUTO);

        app_bar_layout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
        lyt_profile = (LinearLayout) view.findViewById(R.id.lyt_profile);

        mSoundCheckBox = view.findViewById(R.id.sound_checkbox);
        mVibrationCheckBox = view.findViewById(R.id.vibration_checkbox);
        populateSoundContents();
        populateVibrationContents();

        mContext = getActivity().getApplicationContext();
        AppController.currentActivity = getActivity();

        ((TextView) view.findViewById(R.id.name)).setText(R.string.setting_heading);
        ((TextView) view.findViewById(R.id.name_toolbar)).setText(R.string.setting_heading);
        ((View) view.findViewById(R.id.lyt_spacer)).setMinimumHeight(Utils.getScreenHeight() / 2);

        hideView(app_bar_layout);
return dialog;
    }
@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

private void switchSoundCheckbox() {
        isSoundOn = !isSoundOn;
        SettingsPreferences.setSoundEnableDisable(mContext, isSoundOn);
        populateSoundContents();
    }

    protected void populateSoundContents() {
        if (SettingsPreferences.getSoundEnableDisable(mContext)) {
            mSoundCheckBox.setChecked(true);
        } else {
            mSoundCheckBox.setChecked(false);
        }
        isSoundOn = SettingsPreferences.getSoundEnableDisable(mContext);
    }
public void viewClickHandler(View view) {
        switch (view.getId()) {
            case R.id.sound_checkbox:
                switchSoundCheckbox();
                break;
}
}

标签: androidandroid-fragmentsandroid-context

解决方案


populateSoundContents()设置mCotext变量后调用。请更改您的代码如下:

mContext = getActivity().getApplicationContext();
populateSoundContents();
populateVibrationContents();

    

推荐阅读