[英]What is the analog of startActivityForResult() but using fragments
我有4個標簽,每個標簽在選中時都會運行一個片段。
從選項卡#2片段中,我想開始另一個片段以在選項卡#2上運行並從中獲取結果。 什么是正確的方法? 周圍有什么例子嗎?
如果這些是活動,而不是片段,我知道我將使用startActivityForResult()。
有一個建議的片段交互模式。 您的每個片段都使用接口聲明了與其他對象交互的方式:
這是第一個片段的代碼:
public class Fragment1 {
private Listener listener;
@Override
public void onCreateView(...) {
Bundle args=getArguments();
if (args!=null) {
Object arg=args.getParcelable("result");
//use the result for something
}
//...
someView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener!=null)
listener.onFragment2Requested();
}
});
//...
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener=(Listener) activity;
}
public interface Listener {
public void onFragment2Requested();
}
}
第二個片段:
public class Fragment2 {
private Listener listener;
@Override
public void onCreateView(...) {
//...
someView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Object object=...
if (listener!=null)
listener.onWorkDone(object);
}
});
//...
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
//will throw ClassCastException unless your Activity
//implements Listener interface of your fragment
this.listener=(Listener) activity;
}
public interface Listener {
public void onWorkDone(Object someResult);
public void someOtherMethod();
}
}
最后是您的Activity
,它是協調者:
public class YourActivity extends
FragmentActivity
implements
Fragment1.Listener,
Fragment2.Listener {
public void onFragment2Requested() {
Fragment2 frg2=new Fragment2();
//here goes your code to switch fragments the way you want
}
public void onWorkDone(Object someResult) {
//if you don't want to create new instance of fragment each time
//you can try to get it from FragmentManager.
//But don't try to store reference to it anywhere (activity field etc.)
//it could interfere with fragment recycling mechanism
Fragment1 frg1=new Fragment1();
Bundle args=new Bundle();
args.putParcelable("result", someResult);
//instead of arguments, you could use setter method, but that way
//your Object is lost when fragment is recreated upon orientation change, etc.
frg1.setArguments(args);
//here goes your code to switch fragments the way you want
}
public void someOtherMethod() {
//...
}
}
我知道,這似乎太多了代碼,但這是完成的方式。 此外,這種模式被覆蓋在這篇文章中 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.