创建一个" Global" AlertDialog

时间:2016-04-08 14:22:57

标签: android

嘿伙计们我试图在其中创建一个带有用户文本输入的AlertDialog 因为在我的应用程序中我至少需要3个,我认为创建一个AlertDialog方法将是一个好主意,它将返回用户在其中键入的值 进入一个特定的方法,并由此节省编写很多代码

以下是我的代码示例

public void alrtDialog(String setTitle, String setPositiveBtn)
{
    AlertDialog.Builder myDialog = new AlertDialog.Builder(context);//<--create alert dialog builder
    myDialog.setTitle(setTitle);
    final EditText myText = new EditText(context);
    myText.setInputType(InputType.TYPE_CLASS_TEXT);
    myDialog.setView(myText);
    Log.e("blalba", "texoutt:" + myText.getText().toString());
    myDialog.setPositiveButton(setPositiveBtn, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            setMsg(myText.getText().toString());//<--set
            Log.e("blalba", "teinxt:" + myText.getText().toString());
        }
    });
    myDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    myDialog.show();
    return getMsg();
}

1 个答案:

答案 0 :(得分:2)

创建DialogFragment

public class MyDialogFragment extends DialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_sample_dialog, container, false);
        getDialog().setTitle("Simple Dialog");
        return rootView;
    }
}

在任何情况下显示

FragmentManager fm = getFragmentManager();
MyDialogFragment dialogFragment = new MyDialogFragment ();
dialogFragment.show(fm, "Sample Fragment");