Implement Dialogfragment Interface In Onclicklistener
Solution 1:
Something like this?
publicclassCustomNumberPickerextendsDialogFragment {
private NoticeDialogListener ndl;
publicinterfaceNoticeDialogListener {
publicvoidonDialogPositiveClick(DialogFragment dialog);
publicvoidonDialogNegativeClick(DialogFragment dialog);
}
//add a custom constructor so that you have an initialised NoticeDialogListenerpublicCustomNumberPicker(NoticeDialogListener ndl){
super();
this.ndl=ndl;
}
//make sure you maintain an empty constructorpublicCustomNumberPicker( ){
super();
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener@OverridepublicvoidonAttach(Activity activity) {
super.onAttach(activity);
//remove the check that verfis if your activity has the DialogListener Attached because you want to attach it into your list view onClick()
}
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builderbuilder=newAlertDialog.Builder(getActivity());
builder.setMessage("Sets")
.setPositiveButton("set", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
ndl.onDialogPositiveClick(dialog);
}
})
.setNegativeButton("cancle", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
ndl.onDialogNegativeClick(dialog);
}
});
// Create the AlertDialog object and return itreturn builder.create();
}
}
and then your listView onClick becomes:
tvSets.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
// This is where the Dialog should be called and// the user input from the Dialog should be returned// // DialogFragment numberpicker = newCustomNumberPicker(newNoticeDialogListener() {
@OverridepublicvoidonDialogPositiveClick(DialogFragment dialog) {
//What you want to do incase of positive click
}
@OverridepublicvoidonDialogNegativeClick(DialogFragment dialog) {
//What you want to do incase of negative click
}
};);
numberpicker.show(MainActivity.this.getSupportFragmentManager(), "NoticeDialogFragment");
}
// Here I would like to implement the interface of CustomNumberPicker// in order to get the user input entered in the Dialog
});
Do read the comments I have added.And it can even be further optimized because you really dont need an entire dialog instance to get the values you need.
EDIT a possible optimization could be:
Changing the Listener interface to :
publicinterfaceNoticeDialogListener {
publicvoidonDialogPositiveClick(String output);
publicvoidonDialogNegativeClick(String output);
//or whatever form of output that you want
}
Then modify the implemented methods accordingly.
Solution 2:
You should have your activity, implement your interface (NoticeDialogListener
).
publicclassMainActivityextendsActionBarActivityimplementsNoticeDialogListener{
@Override
public void onDialogPositiveClick(DialogFragment dialog){
//Do something
}
@Override
public void onDialogNegativeClick(DialogFragment dialog){
//Do some other things
}
[...]
}
Then in your button click listeners of the dialog, you use the mListener
and call the methods, which is now implemented in the activity and the code will be executed there.
builder.setMessage("Sets")
.setPositiveButton("set", new DialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
if(mListener != null)
mListener.onDialogPositiveClick(CustomNumberPicker.this);
}
});
Also note that you should set the mListener
to null in the onDetach()
method of your DialogFragment.
@OverridepublicvoidonDetach() {
super.onDetach();
mListener = null;
}
Solution 3:
Here's how it's done: In the Activity where you show the DiaogFragment, set the arguments of the DialogFragment with the desired name value pair. Also make sure that the activity implements the DialogInterface.OnClickListener In the overridded onClick pick up the value from the aforementioned name value pair
publicclassMainActivityextendsAppCompatActivityimplementsDialogInterface.OnClickListener {
privatestatic SettingsFragment settingsFragment;
private Button btnSettings;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnSettings = (Button) findViewById(R.id.btnSettings);
btnSettings.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
settingsFragment = newSettingsFragment();
Bundlebundle=newBundle();
bundle.putString("myKey", null);
settingsFragment.setArguments(bundle);
//Use the commented out line below if you want the click listener to return to a fragment instead of an activity//assuming that this class in a fragment and not an activity//rotateSettingsFragment.setTargetFragment(getActivity().getSupportFragmentManager().findFragmentByTag("TagForThisFragment"), 0);
settingsFragment.setTargetFragment(settingsFragment, 0);
settingsFragment.setCancelable(true);
settingsFragment.show(getSupportFragmentManager(), "SettingsFragment");
}
});
}
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
if(getResources().getResourceEntryName(which).equals("btnSettingFragmentClose")) {
StringmyValue= settingsFragment.getArguments().getString("myKey");
dialog.dismiss();
}
}
}
In your DialogFragment declare a DialogInterface.OnClickListener and cast it to the activity in the onAttach. In the event that needs to send back the data to the activity; set the buddle arguments and then call the onClickListener.onClick
public class SettingsFragment extends DialogFragment {
privateView rootView;
privateButton btnSettingFragmentClose;
privateDialogInterface.OnClickListener onClickListener;
publicSettingsFragment() {}
/* Uncomment this and comment out on onAttach when you want to return to a fragment instead of an activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onClickListener = (DialogInterface.OnClickListener) getTargetFragment();
}
*/@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_settings, container, false);
btnSettingFragmentClose = (Button) rootView.findViewById(R.id.btnSettingFragmentClose);
btnSettingFragmentClose.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
getArguments().putString("myKey", "Hello World!");
onClickListener.onClick(getDialog(), v.getId());
}
});
return rootView;
}
@OverridepublicvoidonAttach(Activity activity) {
super.onAttach(activity);
try {
onClickListener = (DialogInterface.OnClickListener) activity;
}
catch (ClassCastException e) {
thrownewClassCastException(activity.toString() + " must implement mainFragmentCallback");
}
}
}
Solution 4:
This simple solution works for me:
publicclassMyActivityimplementsMyDialogFragment.Listener {
// ...@OverridepublicvoidonMyEvent() {
// do something here
}
}
publicclassMyDialogFragmentextendsDialogFragment {
private Listener mCallback;
publicinterfaceListener {
voidonMyEvent();
}
@SuppressLint("RestrictedApi")@OverridepublicvoidsetupDialog(final Dialog dialog, int style) {
super.setupDialog(dialog, style);
ViewcontentView= View.inflate(getContext(), R.layout.dialog_fragment_custom, null);
dialog.setContentView(contentView);
mCallback = (Listener) getActivity();
ButtonmyBtn= (Button) dialog.findViewById(R.id.btn_custom);
myBtn.setOnClickListener(v -> {
mCallback.onMyEvent();
dismiss();
});
}
}
Solution 5:
As an example you can use DatePickerDialog where DatePickerDialog.OnDateSetListener used to deliver result.
or this is one of my implementations that allow to keep dialog screen open until user not finished with some action or not entered valid data. With custom callback that provide exact interface to this dialog.
publicclassConfirmPasswordDialogextendsDialogFragment {
private OnPaswordCheckResult resultListener;
private TextView passwordView;
publicConfirmPasswordDialog(OnPaswordCheckResult resultListener){
this.resultListener = resultListener;
}
@Overridepublic android.app.Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builderbuilder=newAlertDialog.Builder(getActivity());
LayoutInflaterinflater= getActivity().getLayoutInflater();
ViewdialogView= inflater.inflate(R.layout.dialog_layout, null);
builder.setView(dialogView);
passwordView = (TextView) dialogView.findViewById(R.id.password);
passwordView.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {/*do nothing*/}
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before, int count) {/*do nothing*/}
@OverridepublicvoidafterTextChanged(Editable s) {
if(passwordView != null){
passwordView.setError(null);
}
}
});
builder.setView(dialogView);
builder.setMessage("Please enter password to finish with action");
builder.setPositiveButton("Confirm", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
/* do something when click happen, in this case mostly like dummy because data return later
* after validation or immediately if required*/
}
});
builder.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setTitle("Confirm password");
finalAlertDialogdialog= builder.create();
dialog.setOnShowListener(newDialogInterface.OnShowListener() {
@OverridepublicvoidonShow(final DialogInterface dialogInterface) {
ButtonpositiveButton= dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(newView.OnClickListener(){
@OverridepublicvoidonClick(View view) {
if(passwordView == null || !isAdded()){
return;
}
Stringpassword= passwordView.getText().toString();
if(PrefUtils.isPasswordValid(getActivity(), password)){
if(resultListener == null){
return;
}
/* Return result and dismiss dialog*/
resultListener.onValidPassword();
dialog.dismiss();
} else {
/* Show an error if entered password is invalid and keep dialog
* shown to the user*/Stringerror= getActivity().getString(R.string.message_password_not_valid);
passwordView.setError(error);
}
}
});
}
});
return dialog;
}
/**
* Custom callback to return result if entered password is valid
*/publicstaticinterfaceOnPaswordCheckResult{
voidonValidPassword();
}
}
Post a Comment for "Implement Dialogfragment Interface In Onclicklistener"