Passing an Object to Fragment or DialogFragment upon Instantiation

痴心易碎 提交于 2021-02-17 21:36:32

问题


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.

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().

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?

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.


回答1:


In your DialogFragmnet class, you create two methods:

  1. newInstance to make instance of your DialogFragment

  2. setter to initialize your object

and add setRetainInstance(true); in 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);
    }
}

then, to show the dialog

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");



回答2:


You can pass Object in the Bundle extras as Parcelable Objects (http://developer.android.com/reference/android/os/Parcelable.html ) and pass them to Bundle in the onCreateView(Bundle savedInstanceState). You can although save them if the user flips the screen.

EDIT: this Parcelable tutorial was quite good!

Another way is getting the data object from your ParentActivity, but I'm not sure if this is a good way (but it works..)

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mYourObject = ((MainActivity) getActivity()).getYourObject();
}

you have to create a Getter in your Activity for that

public YourObject getYourObject(){
   return mYourObecjt;
}

But I guess Parcelables are the better way, because you can reuse your Fragments without any dependencies...




回答3:


You could always use a nice JSON library like GSON or Genson for serializing objects - it is my goto approach for any remotely complex object. GSON is slightly more compact for simple operations but if you have any sort of inheritance / polymorphism in your views, I would highly recommend Genson. You can have a ctr with argument aslong as you document them.

https://code.google.com/p/genson/ - Get the JAR in the download section.




回答4:


I fixed my need with sharepreference. YuzdeDataUser is my Custom clas that I take it onClickItemListener from My Listview

How to Send

  YuzdeDataUser clickedObj = (YuzdeDataUser) parent.getItemAtPosition(position);
            //clickedObj.setTarihim();
            SharedPreferences shp = getSharedPreferences("sam", MODE_PRIVATE);
            SharedPreferences.Editor editor = shp.edit();

            Gson gson = new Gson();
            String json = gson.toJson(clickedObj);
            editor.putString("yoklamaList", json);
            editor.commit();

            FragmentManager fragmentManager = getSupportFragmentManager();
            AylikRaporPop userPopUp = new AylikRaporPop();
            userPopUp.show(fragmentManager, "sam");

How to Receive

    SharedPreferences shp = parent.getSharedPreferences("sam", MODE_PRIVATE);
    SharedPreferences.Editor editor = shp.edit();

    Gson gson = new Gson();
    String json = shp.getString("yoklamaList", "");
    YuzdeDataUser user = gson.fromJson(json, YuzdeDataUser.class);
    if (user != null) {
        txt_ad.setText(user.getAd());
        txt_tur_tarih.setText(Util.getInstance(parent).writeNameOfTur(user.getTur_id()));
        txt_var.setText("" + user.getVar());
        txt_gorevli.setText("" + user.getGorevli());
        txt_yok.setText("" + user.getYok());

    }


来源:https://stackoverflow.com/questions/16405825/passing-an-object-to-fragment-or-dialogfragment-upon-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!