您提到您有自己的对话框/弹出窗口的 xml 布局,这是另一种解决方案,与 Jarvis 的解决方案略有不同。
public class SomeDialog extends DialogFragment {
public interface SomeDialogListener {
void onSomethingChanged(some argument);
}
private static final String DIALOG_ARGUMENT_SOMEARGUMENT= "someTag";
private SomeDialogListener mListener;
public static SomeDialog newInstance(...params) {
SomeDialog someDialog= new SomeDialog();
Bundle args= new Bundle();
args.putInt(DIALOG_ARGUMENT_DURATION, minutes);
someDialog.setArguments(args);
return someDialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle arguments= getArguments();
int duration= arguments.getInt(DIALOG_ARGUMENT_SOMEARGUMENT, DEFAULT_VALUE);
View view= inflater.inflate(R.layout.template_edit_duration_dialog, container);
getDialog().setTitle(R.string.YourTitle);
setupOKButton(view);
setupCancelButton(view);
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener= (SomeDialogListener) activity;
} catch (ClassCastException e) {
throw new IllegalStateException(activity.toString() + " must implement SomeDialogListener");
}
}
private void setupOKButton(View view) {
final View okButton= view.findViewById(R.id.okButton); // From layout
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do something, dismiss dialog ( e.g. getDialog().dismiss(); or call listener mListener.onSomethingChanged(argument) )
}
});
}
private void setupCancelButton(View view) {
final View cancelButton= view.findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do something, dismiss dialog (e.g. getDialog().dismiss();)
}
});
}
现在可以使用 SomeDialog.newInstance(params).show(FragmentManager, DialogTag (optional)) 实例化对话框。使用 Dialog 的类还应该实现您创建的 dialogListener。
如果您只需要一个对话框来通知用户某些事情,您可以使用 AlertDialog 或只使用 Jarvis 建议的对话框。