Reputation: 63
It is defacto that when you need to pass an argument to a custom dialog fragment, you bundle it up before actually using them.
Example:
class MyDFrag extends DialogFragment{
//Empty Construct
public MyDFrag(){}
public static MyDFrag newInstance(){
MyDFrag fragment = new MyDFrag();
args = new Bundle();
fragment.setArgument(args);
}
}
This works splendid for the most path but only if you pass this arguments before actually showing the dialog fragment.
My problem is that i have a textview in my dialog and want to change its value when something happens in its parent activity while the dialog is currently showing.
Passing the argument after showing the dialog doesn't effect this change.
In my onCreate:
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textbox = (TextView) view.findViewById(R.id.textish);
if(args.containsKey("status")){
textbox.setText(getArguments().getString("status"));
}
}
In the dialog class, i have a public dialog that set the value of the textview which i then call in my main activity at some point.
public void setStatus(String value){
args.putString("status", value);
}
So when i'm ready in my main activity, i call
dialog.setStatus("ok");
This only works if i run code before showing the dialog not whilst its showing. Is there a way to achieve this?
Suggestion are appreciated, Thanks
Upvotes: 1
Views: 479
Reputation: 76
public void setStatus(String value){
if(textbox!=null){
textbox.setText(value);
}else{
args.putString("status", value);
}
}
Upvotes: 0
Reputation: 608
From what you posted, the code does not detect when there's a change to args, and so it doesn't read from args again to set your changes.
But it's pointless to set the args in the first place if all your doing is just read from them again once, instead I recommend you set the text in your setStatus method directly like so (can't get code formatting to work right for some reason):
public void setStatus(String value){
textbox.setText(value);
}
Please note that user facing code should never be hardcoded, instead use string resources.
Upvotes: 0
Reputation: 941
I believe there are several ways to do this. Basically, as I see it, what you want is to be able to send a message asynchronously to the dialog that something has changed and the UI needs updating. I would suggest looking into using a LocalBroadcastManager : https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
It's really simple to use - not much code to set it up. You can find plenty of examples of how to use them. I would then setup a receiver in the dialog when it is created or shown. In your parent activity when you need to inform the dialog of changes, you would then fire off a message with the data.
Upvotes: 1