Android:使用Fragment内部调用AlertDialog时出错

时间:2013-12-19 03:21:23

标签: android android-fragments android-alertdialog

当我尝试从我的片段调用AlertDialog时,为什么总是会出错? 起初我尝试将它放在OnCreate中,但它也得到相同的错误日志...

MainFragment.java

public class MainFragment extends Activity {

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

        if (savedInstanceState == null) {
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            LoginFragment fragment = new LoginFragment();
            ft.add(R.id.simple_fragment, fragment).commit();
        }

    }

}

LoginFragment.java

public class LoginFragment extends Fragment implements OnClickListener {

    Helper application;

    static LoginFragment newInstance() {
        LoginFragment f = new LoginFragment();

        Bundle args = new Bundle();
        f.setArguments(args);

        return f;
    }

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

    }

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

        AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity().getApplicationContext());
        dlgAlert.setMessage("TEST");
        dlgAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        });
        dlgAlert.setCancelable(false);
        dlgAlert.create().show();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_login, container, false);

        Button inner = (Button) v.findViewById(R.id.btnSignUp);
        inner.setOnClickListener(LoginFragment.this);

        return v;
    }

    @Override
    public void onClick(View v) {

    }

}

这是错误日志

12-19 10:14:25.295: E/AndroidRuntime(1083): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.fragment.MainFragment}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

以前有人见过这个吗?

2 个答案:

答案 0 :(得分:1)

试试

AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());

答案 1 :(得分:0)

如果您正在处理嵌套片段。当片段拥有自己的子片段时,您需要使用getChildFragmentManager()