从MainActivity启动AlertDialog片段

时间:2015-05-19 21:16:23

标签: android android-fragments fragment alertdialog android-fragmentactivity

我确定有一个简单的答案。我试图在没有按钮的情况下从主活动中启动AlertDialogFragment(RegForXapo)。当我点击正面或负面按钮时,它会弹出,但app力会关闭。

这是我的主要

sharedPref = getSharedPreferences(mypref, Context.MODE_PRIVATE);
    if (sharedPref.getBoolean("firstRun", true)) {
        //start AlertDialog
        FragmentManager fm = getSupportFragmentManager();
        RegForXapo reg = new RegForXapo();
fm.show(reg, "dialog");
    }

这是我的对话

import android.os.Bundle;
import android.app.DialogFragment;
import android.app.Dialog;
import android.app.*;
import android.content.DialogInterface;
import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.net.Uri;


 import android.content.*;public class RegForXapo extends DialogFragment
 {
    private Context context;

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.xapoask);
    builder.setPositiveButton(R.string.positivebutton, 
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //dismiss dialog and set to never appear. take user to xapo reg
            SharedPreferences sharedPref = context.getSharedPreferences("MySharedPrefs",0);
            Editor editor = sharedPref.edit();
            editor.putBoolean("firstRun",false);
            Intent launchBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
            startActivity(launchBrowser);

        }
    });
    builder.setNegativeButton(R.string.negativebutton, 
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //dismiss dialog and set to never appear
            SharedPreferences sharedPref = context.getSharedPreferences("MySharedPrefs",0);
            Editor editor = sharedPref.edit();
            editor.putBoolean("firstRun",false);

        }
    });
    builder.setNeutralButton(R.string.neutralbutton,
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            //dismiss dialog and set to reappear
            // no code necesary
        }


    });


    return builder.create();
}

 }

1 个答案:

答案 0 :(得分:1)

创建一个RegForXapo(DialogFragment)对象,然后show

sharedPref = getSharedPreferences(mypref, Context.MODE_PRIVATE);
if (sharedPref.getBoolean("firstRun", true)) {
    //start AlertDialog
    FragmentManager fm = getSupportFragmentManager();
    RegForXapo regForXapo = new RegForXapo();
    regForXapo.show(fm, "dialog");
}