lundi 29 mai 2017

How to comunicate ParentFragment to ChildFragment

I used to use the combination of Activity, Fragment, ChildFragment.

for example,

class ParentFragment extends SpecificPurposedFragment{

    void onCreateView(){
        FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
        ChildFragment childFragment = ChildFragment.newInstance();
        bt.add(childFragment, DIALOG);
        bt.commitAllowingStateLoss();
    }

    int count(){
        return dataList.size();
    }
}

class ChildFragment extends Fragment {

    void onEvent(){
    // When event is invoked, childFragment have to know ParentFragment State
    if(getParentFragment() instanceOf SpecificPurposedFragment){
        int count = ((ParentFragment)getParentFragment()).getCount();
        // UI handling by count.
    }
}

}

in this case, for child Fragment know parentFragment state, ChildFragment use TYPE-CASTING ParentFragment to SpecificPurposedFragment. It has STRONG-DEPENDENCY.

How to be solved it? (condition: more lower DEPENDENCY)

Aucun commentaire:

Enregistrer un commentaire