I have Activity in my app with few fragments in it. One of these fragments has a DialogFragment, it called by button click. DialogFragment has 3 buttons - positive, negative and neutral.
public class CompanyNotConnectedToSRDialog extends DialogFragment {
public static final String TAG = CompanyNotConnectedToSRDialog.class.getSimpleName();
private NotConnectedDialogListener mNotConnectedDialogListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity(), R.style.DefaultAlertDialogTheme)
.setTitle("Register")
.setMessage("Do you really want to register?")
.setNeutralButton("Skip", (dialog1, which) -> {
mNotConnectedDialogListener.onSkipBtnNotConnectedDialogPressed();
})
.setNegativeButton("Cancel", null)
.setPositiveButton("Register", (dialog12, which) -> {
mNotConnectedDialogListener.onSendBtnNotConnectedDialogPressed();
})
.create();
}
public interface NotConnectedDialogListener {
void onSkipBtnNotConnectedDialogPressed();
void onSendBtnNotConnectedDialogPressed();
}
public void setListener(NotConnectedDialogListener listener) {
this.mNotConnectedDialogListener = listener;
}
As you can see I created public interface that contains two methods for my skip and register buttons (cancel button listener is null so it doesn't matter) and the Setter for this listener.
Then I implemented this interface in my fragment that calls this dialogFragment, I Overrided methods and called dialogFragment like this:
if (mNotConnectedDialog == null) {
mNotConnectedDialog = new CompanyNotConnectedToSRDialog();
mNotConnectedDialog.setListener(this);
mNotConnectedDialog.show(getActivity().getFragmentManager(), CompanyNotConnectedToSRDialog.TAG);
} else {
mNotConnectedDialog.show(mActivity.getFragmentManager(), CompanyNotConnectedToSRDialog.TAG);
mNotConnectedDialog.setListener(this);
}
The problem is I get NullPointerException if I press the button in my parent Fragment to show DialogFragment, rotate screen and press any button in my DialogFragment, because my listener is null.
java.lang.NullPointerException: Attempt to invoke interface method 'void com.myapp.ui.object.create.dialogs.CompanyNotConnectedToSRDialog$NotConnectedDialogListener.onSendBtnNotConnectedDialogPressed()' on a null object reference
at com.myapp.ui.object.create.dialogs.CompanyNotConnectedToSRDialog.lambda$onCreateDialog$1(CompanyNotConnectedToSRDialog.java:31)
How to handle these clicks and set listeners if this solution is wrong?
PS: please don't tell me about android:configChanges.
So the current solution doesn't work because when you rotate the dialog fragment is destroyed and recreated. So setListener isn't called. The solution depends on if your listener is an activity or another fragment.
If it's an activity you can override onAttach in your DialogFragment and set the listener there. If your listener is a fragment then in your OnCreateDialog method you can look the fragment up by the tag and set the listener that way. For example.
Fragment listenerFragment = getActivity().getSupportFragmentManager().findFragmentByTag(getString(R.string.your_listener_fragment_tag));
if( listenerFragment instanceOf NotConnectedDialogListener ) {
listener = (NotConnectedDialogListener) listenerFragment;
} else {
//Handle what to do if you don't have a listener here. Maybe dismiss the dialog.
}
Yes, after orientation change your listener is null. It's easiest to do the callback to the activity:
public static class DialogFragmentA extends DialogFragment {
// Container Activity must implement this interface
public interface NotConnectedDialogListener {
public void onX();
}
NotConnectedDialogListener mListener;
...
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NotConnectedDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement NotConnectedDialogListener");
}
}
...
}
Now you can call mListener.onX etc. in your dialog anywhere, also after orientation change. Your container Activity must implement the interface and will receive the method call.
https://developer.android.com/guide/components/fragments.html#EventCallbacks
Related
I am creating a custom dialog class in which I extend the default Dialog. I am doing some work there. Once the user closes the dialog, how can my activity know that the dialog is closed and time to update the screen views with results?
Do I pass an instance from my activity to the Dialog class so I can call a public method on it? Or is there a better design?
Thank you
what I'll do is this:
Create an Interface, for example: OnDialogCloseListener, with a method called onDialogClose()
The activity have to implement that interface and override the onDialogClose() method
Create an attribute in yout Dialog class of OnDialogCloseListener type and a constructor method and when you create the Dialog pass the activity as a parameter.
OnDialogCloseListener listener;
public MyDialog(OnDialogCloseListener listener) {
this.listener = listener;
}
Now in your onClick method of the close button of your Dialog call the method of the interface. Ex.:
listener.onDialogClose();
And finally in your activity class in the method that you override from OnDialogCloseListener do whatever you want when the Dialog is close.
Note: You can create all the methods that you want in the interface a call each one whatever you want, not only when the dialog is close, you may have other events that you want check when raised.
Hope that can help you
From the docs: http://developer.android.com/guide/topics/ui/dialogs.html
create an interface in your dialog class:
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
Register a listener in onAttach() :
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
And implement that interface in your calling activity.
A dialog overrides several methods that sense when the dialog is closing. The include
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public void setOnCancelListener(#Nullable OnCancelListener listener) {
super.setOnCancelListener(listener);
}
#Override
protected void onStop() {
super.onStop();
}
These methods all detect that action of closing a dialog. However, the most efficient one that I suggest you use is
#Override
public void onDetachedFromWindow() {
Toast.makeText(getContext().getApplicationContext(), "Dialog had disappeared", Toast.LENGTH_SHORT).show();
super.onDetachedFromWindow();
}
I have a DialogFragment class. I have to set the listener every time it shown (It has multiple cases in my app).
But when I rotate the screen mListener becomes null and there is a NullPointerExcpetion when I click a button. I can't implement the listener in the activity because it has a few cases for this dialog, each has different action.
The CustomDialog class:
MyDialogListener mListener;
public void show(FragmentManager fm, MyDialogListener listener) {
mListener = listener;
super.show(fm, "MyDialog");
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setPositiveButton(android.R.string.ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
mListener.onDialogPositiveClick();
// NullPointerException after a screen rotate
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
The activity class:
public void showMyFirstDialog() {
new CutsomDialog().show(getFragmentManager(), mFirstListener);
}
public void showMySecondDialog() {
new CutsomDialog().show(getFragmentManager(), mSecondListener);
}
You cannot preserve instance fields of a Fragment (including a DialogFragment). The mechanism for having local data survive configuration changes is to set the fragment's arguments to a Bundle that contains your data; this bundle will survive configuration changes.
First, eliminate the show() method; it's not the correct approach. Instead, you can do something like this:
DialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putString("TITLE", "Dialog Title Goes Here");
args.putString("MESSAGE", "This is a dialog messaage");
frag.setArguments(args);
frag.show();
Then you can retrieve the title and message when you create the AlertDialog:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
String title = args.getString("TITLE");
String message = args.getString("MESSAGE");
// set up and return the alert dialog as before
}
Dealing with the DialogListener is a little more complex. You don't want to be holding a reference to that across config changes because it will lead back to the destroyed activity. Instead, you can arrange to retrieve the listener from the activity inside the fragment's onAttach() method:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// now cast activity to your activity class and get a reference
// to the listener
}
You may need to change your activity class(es) a bit to get this to work right. If you're using this dialog fragment from many activities, it's particularly helpful here to define an interface that the activities can implement to request a listener. It would then look something like this:
public interface DialogListenerProvider {
DialogListener getDialogListener();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof DialogListenerProvider) {
mListener = ((DialogListenerProvider) activity).getDialogListener();
} else {
// throw an error
}
}
The listener should not be passed in as an argument but instead implemented as part of interface both within the dialogfragment itself and may be an activity. That way, when the positive / negative click happens, you can update data on something and pass it to listener. The listener, when implemented by activity, would pass on the data to teh activity and you can take corresponding action in activity then.
Check these few examples -
http://www.i-programmer.info/programming/android/7426-android-adventures-custom-dialogs-using-dialogfragment.html?start=2
http://android-developers.blogspot.com/2012/05/using-dialogfragments.html
Hope it helps.
I have one MainActivity and two fragments namely Input.java and Output.java. I want to access the textview located at output_layout in Input fragment (More precisely, if I click on the button in input_layout, the textview of output_layout should change). How can i do this? I am calling these input_layout and out_put layout dynamically in main_activity.
As I am beginner, pardon my ignorance. Your help will be highly appreciated. Thanks in advance.
Try use interfaces.
For example.
public interface OnOutputFragmentTextChanger {
public void onChangeText(String what);
}
In onAttach method of Input.class do next:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnOutputFragmentTextChanger) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnOutputFragmentTextChanger");
}
}
And in yours OnClickListener call mCallback.onChangeText("Foooo");
Next in Output class create method
public void updateInputView(String what)
{
mTextView.setText(what);
}
Next implement OnOutputFragmentTextChanger in Activity and Override method onChangeText(String what):
public class MainActivity extends FragmentActivity implements OnOutputFragmentTextChanger
{
//do somwthing
#Override
public void onChangeText(String what)
{
InputFragment inputfragment = (InputFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment); // or try findFragmentByTag
if (inputfragment != null)
{
inputfragment.updateInputView("some string");
}
}
}
you can declare the TextView in the input layout as public static in the corresponding fragment and directly access it in other fragment where you want to set the value onclick of the button
Here is what I would like to do:
1) Inside an Activity a dialog is shown. I use DialogFragment and FragmentManager for this, by calling:
dialogFragment.show(fragmentManager, "edit_task_list");
2) Inside the Dialog I have layout with a custom Button. I would like to perform some action when the button is clicked and later close the dialog.
How should I connect everything? I see two options:
1) onclick attribute in the Button and a method inside the Actvity. That was my original plan, but I don't how to get the Dialog from the Activity to dismiss it. Even if this is not the right way, how could this be done? I would like to understand how this works.
2) set on click listener on the button when the Dialog is created in DialogFragment. This will require me to pass some context from the Activity to the DialogFragment, so I would like to avoid it (and keep the DialogFragment as simple as possible).
Which of those options should I take?
Number 2 Doesn't require you to pass any context (and you shouldn't). You define an interface that can act as a contract between fragments and activities and make your activity implement it.
From your dialog and in your button.onClick(), you do something like this (untested code):
if ( getActivity() != null
&& !getActivity().finishing()
&& getActivity() instanceOf YourInterface) {
((YourInterface)getActivity()).onSomeNiceMethod();
dismiss(); // close the dialog (if this is what you want).
}
The interface looks like:
public interface YourInterface {
void onSomeNiceMethod();
}
And your Activity…
public class YourActivity implements YourInterface {
void onSomeNiceMethod() {
// Hey! The Button In The Dialog Has Been Pressed!
}
}
All Activity and Fragment classes have a built-in callback method for you to use when you start another Activity, Fragment, Dialog, or DialogFragment.
void onActivityResult(int requestCode, int resultCode, Intent data)
Since you want to start the Dialog from an Activity, using the Dialog class is better than the DialogFragment class. The latter is better for starting a dialog from a Fragment, because it has two methods for communicating back to the Fragment (get/set TargetFragment())
The Dialog class has the getOwnerActivity() method. This is the Activity you use when creating the Dialog with one of its constructors.
You set a onClickListener on the button in the Dialog class. To pass the result back to the Activity:
getOwnerActivity().onActivityResult(intIdentifyingme, Activity.RESULT_OK,
intent);
dismiss(); // close the dialog
You put additional info you want to send in an Intent.
1) onclick attribute in the Button and a method inside the Actvity.
That was my original plan, but I don't how to get the Dialog from the
Activity to dismiss it. Even if this is not the right way, how could
this be done? I would like to understand how this works.
Basically your Activity has to remember/know which dialog is active at the moment with something like curDialog=dialogFragment;, then when handling the button onclick action you'll know which dialog to dismiss. But this is really not a good idea since basically the Button View would "leak" from your DialogFragment to your Activity, which breaks object encapsulation.
2) set on click listener on the button when the Dialog is created in
DialogFragment. This will require me to pass some context from the
Activity to the DialogFragment, so I would like to avoid it (and keep
the DialogFragment as simple as possible).
As a previous answer mentioned, you don't need to pass any Context to it, especially since you can get the Activity by calling getActivity().
The solution depends on whether or not this dialog would be used by multiple Activities:
Used by a single Activity: #Martin's solution will work just fine
Used by multiple Activity: abstraction can be used such that only the user's decision is passed to a listener. This is a (modified) solution I came up for the same problem:
public class BaseDialogFragment extends DialogFragment {
protected TextView dialogEn;
protected Button dialogYes;
private Button dialogNo;
protected OnSelectListener listener;
public interface OnSelectListener {
public void onSelect(int type, boolean yes);
}
public void setOnSelectListener(OnSelectListener listener) {
this.listener = listener;
}
public BaseDialogFragment() {
super();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_confirm, container, false);
dialogYes = (Button) v.findViewById(R.id.yes);
dialogNo = (Button) v.findViewById(R.id.no);
dialogEn = (TextView) view.findViewById(R.id.dialog_en);
dialogEn.setText(getArguments().getString("text_en"));
dialogYes.setOnClickListener(this);
dialogNo.setOnClickListener(this);
return v;
}
public void onClick(View v) {
if (listener != null) {
listener.onSelect(getArguments().getInt("type"),
v == dialogYes ? true : false);
}
getDialog().dismiss();
}
}
To use it some additional info needs to be provided:
Bundle bundle = new Bundle();
bundle.putInt("type", type); //type: an unique integer value that helps differentiate result from different dialogs
bundle.putString("text_en", en); //en: String to be displayed
dialog.setArguments(bundle);
dialog.setOnSelectListener(this);
So if the type value above is set to 115, then a dialogYes button click would trigger public void onSelect(int type, boolean yes) method to be called with 115 and true as the 1st & 2nd parameters.
Your first point about the onClick attribute in the xml should be avoided. Because handling a Dialog that way could be really painfull if you respect events like screen rotation or a setup with multiple dialogs. This leads into leaked window errors most of the time and needs unnecessary code overhead to avoid this. Because you have to keep track of the Dialog which is actually shown yourself.
To be able to dismiss the Dialog this way you can use the Tag you setted as you called dialogFragment.show(fragmentManager, "edit_task_list");
DialogFragment frag = (DialogFragment)getFragmentManager().findFragmentByTag("edit_task_list");
if(frag != null)
frag.dismiss();
The proper solution is to use an interface as a callback for the communication between the DialogFragment and the Activity. This keeps the Dialog modular and the code easy. Here is an example from the docs. For this you don't need a Context. You simply pass the interface to the dialog in the onAttach() callback. It has a reference of the Activity as a parameter, which called that Dialog.
// Example interface for the communication
public interface OnArticleSelectedListener {
public void onButtonClicked(/*any Parameters*/);
}
public static class FragmentA extends DialogFragment {
OnArticleSelectedListener mListener;
...
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity; // get the interface of the Activity
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnArticleSelectedListener");
}
}
...
}
Handle the Button click in the Dialog and call dismiss() in it, that the Dialog can dismiss itself. Have a look at this question why to use dismiss() instead of getDialog().dismiss().
yourButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
if(mListener != null) // check if the listener is still valid
mListener.onButtonClicked(...); // calls the Activity implementation of this callback
dismiss(); // dismiss the Dialog
}
});
In onPause() of the Dialog set the reference of the interface to null. This way you can be sure that the callback will only be used if the Dialog is showing.
Your Activity looks something like this to be able to handle the callback:
public class MyActivity extends Activity implements OnArticleSelectedListener{
...
#Override
public void onButtonClicked(...){
// your implementation here
}
}
I don't know your overall setup but if you would use an AlertDialog a click on the Buttons dismiss the Dialog automatically when the method returns.
I have created a DialogFragment with a custom AlertDialog that I need to show on several points of my application. This dialog asks for the user to input some data.
I would like to find a way to make the activity where the dialog is called upon to wait for the users input and then perform a variable action when the user presses the ok button (or nothing if he presses cancel).
AFAIK there's no "modal dialog" in Android so what would be the proper way to achieve this (pretty usual) kind of behavior?
To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.
public class MyDialogFragment extends DialogFragment {
OnDialogDismissListener mCallback;
// Container Activity must implement this interface
public interface OnDialogDismissListener {
public void onDialogDismissListener(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnDialogDismissListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnDialogDismissListener");
}
}
...
}
In dialog Ok listener add
mCallback.onDialogDismissListener(position);
In your activity
public static class MainActivity extends Activity
implements MyDialogFragment.OnDialogDismissListener{
...
public void onDialogDismissListener(int position) {
// Do something here to display that article
}
}