Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

android - How to pass data from a fragment to a dialogFragment

I know that this was asked before, but I dont quite understand how to implement it. I have a fragment "myFragment" in which I create an object of a "myDialogueFragment". I want to pass some value to the myDialogueFragment when I invoke it from the myFragment. I have an integer num, that I want to pass to the myDialogueFragment and store that number in a local database along with some other info from the myDialogueFragment.

I might be mistaken, but all the code I have seen is about sending data from the myDialogueFragment back to the myFragment which is not what I really want.

static MyDialogFragment newInstance(int num) {

MyDialogFragment f = new MyDialogFragment();

// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);

return f;
}  

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mNum = getArguments().getInt("num");
    ...
}

So, this code gets the arguments within the myFragment onCreate() method. I want to sent the arguments within the myFragment() and receive them in the myDialogueFragment.

How can I achieve that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you need is to setArguments on the fragment as follows:

Bundle args = new Bundle();
args.putString("key", "value");
DialogFragment newFragment = new YourDialogFragment();  
newFragment.setArguments(args);
newFragment.show(getSupportFragmentManager(), "TAG");

All you have to do now, is catch those arguments in your fragment and use them...

AND IN THE DIALOG FRAGMENT YOU READ IT LIKE THIS...

Bundle mArgs = getArguments();
String myValue = mArgs.getString("keyUsed to send it...");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...