How to update Android fragment from activity?

前端 未结 2 721
傲寒
傲寒 2020-12-31 11:46

I want to periodically update a fragment\'s display based on data I download from the Internet. I have created a Timer and Runnable to periodically retrieve this data as w

2条回答
  •  鱼传尺愫
    2020-12-31 12:17

    You cannot give your fragments a tag or id but you can create a custom property on your fragment class to mark them.

    switch (position)
        {
        case FRAG1_POS:
            Fragment1 f = Fragment1.newInstance();
            f.fragmentType = 1;
            return f;
    
        case FRAG2_POS:
            Fragment1 f = Fragment1.newInstance();
            f.fragmentType = 2;
            return f;
    
        default:
            return null;
        }
    

    When can then loop through all the fragments and find the one you need

    List allFragments = getSupportFragmentManager().getFragments();
    if (allFragments != null) {
        for (Fragment fragment : allFragments) {
            Fragment1 f1 = (Fragment1)fragment;
            if (f1.fragmentType == 1)
                f1.updateFragmentData();
        }
    }
    }
    

    Add a public method to your fragment that will update the data in your fragment. As you have a reference to it now, you can just call it from your activity.

提交回复
热议问题