实例化时将对象传递给片段或DialogFragment

Ker*_*rry 13 android fragment android-fragments android-dialogfragment

我正在尝试找出将对象传递给FragmentDialogFragment的正确方法,而不会破坏" 空构造函数 "规则.

例如,我创建了一个自定义视图,并为每个实例化我想要关联DiaglogFragment.此DialogFragment将用于显示控件,用户可以使用该控件更改与其关联的自定义View的某些方面.因为View是一个对象我理解我不能使用setArguments().

我可以实现我的DialogFragment即工厂模式的newInstance(View)方法,但是如果我的Fragment被系统保存然后在以后恢复会发生什么?据我所知,没有对View对象的引用?

有人可以告诉我,我是否以错误的方式使用碎片,或者是否有办法将对象传递给碎片,这也将处理稍后重建它的系统.

Kar*_*Aly 14

在您的DialogFragmnet课程中,您创建了两个方法:

  1. newInstance 做你的例子 DialogFragment

  2. setter初始化你的对象

并加setRetainInstance(true);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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,显示对话框

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");
Run Code Online (Sandbox Code Playgroud)

  • 不确定这是一个好方法,因为您的DialogFragment可以自动恢复(例如在旋转期间),然后*yourVar*值将为null.因此,如果系统自动实例化,DialogFragment将被错误地呈现. (3认同)

lon*_*ngi 3

您可以将 Bundle extras 中的对象作为 Parcelable 对象 ( http://developer.android.com/reference/android/os/Parcelable.html ) 传递,并将它们传递给onCreateView(Bundle savedInstanceState). 如果用户翻转屏幕,您可以保存它们。

编辑: 这个Parcelable 教程非常好!

另一种方法是从 ParentActivity 获取数据对象,但我不确定这是否是一个好方法(但它有效......)

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mYourObject = ((MainActivity) getActivity()).getYourObject();
}
Run Code Online (Sandbox Code Playgroud)

你必须在你的 Activity 中创建一个 Getter

public YourObject getYourObject(){
   return mYourObecjt;
}
Run Code Online (Sandbox Code Playgroud)

但我认为 Parcelables 是更好的方法,因为你可以重用你的 Fragment 而无需任何依赖......

  • 不确定 Parcelable 是我需要的,但阅读完链接后,我意识到我可能没有清楚地表达我的问题。我需要对实际对象的引用。Parcelable 对象是实际对象的重建/克隆?我需要参考,以便我可以实时更改视图。 (3认同)