首先创建一个base
DialogFragment来保持的实例
Activity。因此,当Dialog附加到时
Activity,您将知道
Activity创建该对话框的Instance
。
public abstract class baseDialogFragment<T> extends DialogFragment { private T mActivityInstance; public final T getActivityInstance() { return mActivityInstance; } @Override public void onAttach(Activity activity) { mActivityInstance = (T) activity; super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); mActivityInstance = null; }}然后,创建一个
GeneralDialogFragment扩展
baseDialogFragment
public class GeneralDialogFragment extends baseDialogFragment<GeneralDialogFragment.OnDialogFragmentClickListener> { // interface to handle the dialog click back to the Activity public interface onDialogFragmentClickListener { public void onOkClicked(GeneralDialogFragment dialog); public void onCancelClicked(GeneralDialogFragment dialog); } // Create an instance of the Dialog with the input public static GeneralDialogFragment newInstance(String title, String message) { GeneralDialogFragment frag = new GeneralDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); args.putString("msg", message); frag.setArguments(args); return frag; } // Create a Dialog using default alertDialog builder , if not inflate custom view in onCreateView @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new alertDialog.Builder(getActivity()) .setTitle(getArguments().getString("title")) .setMessage(getArguments().getString("message")) .setCancelable(false) .setPositiveButton("OK", new DialogInterface.onClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Positive button clicked getActivityInstance().onOkClicked(GeneralDialogFragment.this); } } ) .setNegativeButton("Cancel", new DialogInterface.onClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // negative button clicked getActivityInstance().onCancelClicked(GeneralDialogFragment.this); } } ) .create(); } }如果您需要使用自己的自定义布局进行对话框,请在中添加布局
onCreateView并删除
onCreateDialog。但是添加点击侦听器,
onCreateView就像我在
onCreateDialog
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_dialog, container, false); return view;}然后,在您
Activity需要实施一个
interface处理操作中
dialog
public class TryMeActivity extends FragmentActivity implements GeneralDialogFragment.onDialogFragmentClickListener { @Override public void onOkClicked(GeneralDialogFragment dialog) { // do your stuff } @Override public void onCancelClicked(GeneralDialogFragment dialog) { // do your stuff }}最后,显示
Dialog从你
Activity需要的时候,这样的
GeneralDialogFragment generalDialogFragment = GeneralDialogFragment.newInstance("title", "message"); generalDialogFragment.show(getSupportFragmentManager(),"dialog");希望这可以帮助。我确信这种方法是最优化的方法之一,但是也可能有不同的方法。



