How to update Android fragment from activity?

前端 未结 2 719
傲寒
傲寒 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 11:56

    Here is something you could try:

    Since you mention updating the fragment from the activity (with retrieved data), you could do something like this:

    In your Runnable or AsyncTask, you can update the adapter with the data retrieved and in your fragment, call the onDatasetChanged() method on the adapter so it will automatically update the view.

    If you have multiple fragments, inside those fragments, you could define an interface and then let the activity implement it and then override the method. From within that method in the activity, update the adapter that holds the data. You will have to make the adapter static!

    I hope this helps!

    0 讨论(0)
  • 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<Fragment> 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.

    0 讨论(0)
提交回复
热议问题