在实例化时将对象传递给Fragment或DialogFragment [英] Passing an Object to Fragment or DialogFragment upon Instantiation
问题描述
我正在尝试找出将对象传递给片段或 DialogFragment 而不会破坏"空构造函数'规则.
I'm trying to work out the correct way to pass in an Object to a Fragment or DialogFragment without breaking the 'empty constructor' rule.
例如,我创建了一个自定义视图,实例化的每个视图都想关联一个DiaglogFragment.此DialogFragment将用于显示控件,用户可以使用这些控件更改与之关联的自定义视图的某些方面.因为View是我所了解的对象,所以我不能使用 setArguments().
For example I have created a custom View and for each one I instantiate I want to associate a DiaglogFragment. This DialogFragment will be used to display controls with which the user can alter certain aspects of the custom View it is associated with. Because View is an Object I understand I cannot use setArguments().
我可以实现DialogFragment的newInstance(View)方法(即工厂模式),但是如果我的Fragment由系统保存然后在以后恢复,会发生什么情况?据我所知,将没有对View对象的引用?
I could implement a newInstance(View) method of my DialogFragment i.e. Factory pattern but then what happens if my Fragment is saved by the system and then restored at a later date? As far as I can tell there will be no reference to the View object?
有人可以告诉我我是否以错误的方式使用了Fragments,或者是否有办法实现将对象传递给Fragment,这也将在以后处理系统时对付它.
Could someone tell me if I am using Fragments in the wrong way or is there way to achieve passing in an object to the Fragment which will also cope with the system reconstructing it at a later time.
推荐答案
在您的 DialogFragmnet
类中,创建两个方法:
In your DialogFragmnet
class, you create two methods:
-
newInstance
来创建您的DialogFragment
设置初始化您的对象
并在 onCreate
public class YourDialogFragment extends DialogFragment {
ComplexVariable complexVar;
public static YourDialogFragment newInstance(int arg, ComplexVariable complexVar) {
YourDialogFragment frag = new MoveSongDialogFragment();
Bundle args = new Bundle();
args.putInt("count", arg);
frag.setArguments(args);
frag.setComplexVariable(complexVar);
return frag;
}
public void setComplexVariable(ComplexVariable complexVar) {
this.complexVar = complexVar;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
然后,显示对话框
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
Fragment prev = manager.findFragmentByTag("yourTag");
if (prev != null) {
ft.remove(prev);
}
// Create and show the dialog.
DialogFragment newFragment = YourFragmentDialog.newInstance(argument, yourComplexObject);
newFragment.show(ft, "yourTag");
这篇关于在实例化时将对象传递给Fragment或DialogFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!