如何使用AlertDialog加载Fragment



我试图在警报对话框响应后加载片段,但当我试图加载logcat时,显示"IllegalStateException:片段未附加到活动"。通常情况下,当片段不再附加到活动之后,您尝试执行工作时,会出现IllegalStateException。但在我的情况下,每件事都很好,我不明白为什么片段没有附加到一个活动。

这是我的主要活动:

使用这个类,我调用DilogCreate,它扩展了DialogFragment。

public class MainActivity extends AppCompatActivity {
Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn= (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DilogCreate(view.getContext(),R.string.tilte,R.string.no,R.string.yes);
            }
        });
    }

这是我的DilogCreate类:

在对话框响应的基础上决定是否可以加载片段,如果对话框响应是的,我在这个类下调用另一个活动名称Second.java,我尝试加载片段。

    public class DilogCreate extends DialogFragment {
        AlertDialog alertDialog;

        public DilogCreate(final Context context, int tilte, int no, int yes) {
            AlertDialog.Builder mAlertDilog = new AlertDialog.Builder(context);
            mAlertDilog.setNegativeButton(yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(context, second.class);
                    startActivity(intent);
                }
            });
            alertDialog = mAlertDilog.create();
            alertDialog.show();
        }
    } 

这是我的Second.java类:

这个类是因为对话框响应而出现的,我试图在这个类下加载片段。

public class Second extends AppCompatActivity {
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loadFragment);
        fragmentManager=getSupportFragmentManager();
        fragmentTransaction=fragmentManager.beginTransaction();
        Myfragment myfragment=new Myfragment();
        fragmentTransaction.replace(R.id.cont,myfragment);
        fragmentTransaction.commit();
}
}

这是MyFragment.java扩展Fragment:

public class Myfragment extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.frag,container,false);
    }
}

Logcat状态:

java.lang.IllegalStateException: Fragment DilogCreate{8aea1d4} not attached to Activity

请帮帮我,伙计们,我不知道为什么会出现这个错误。

new DilogCreate(view.getContext(),R.string.tilte,R.string.no,R.string.yes);

传递MainActivity.this而不是view.getContext()。您需要在此处传递活动上下文。

片段加载在活动上,并且通过使用基本引用将一个活动切换到另一个活动,这就是为什么我需要使用基本活动引用调用startActivity()方法。

所以我把DilogCreate类中的startActivit()方法改成这样:

Intent intent=new Intent(context,Second.class);
context.startActivity(intent);//make sure context is the refrence of the base context

最新更新