How to pass data from activity to fragment

前端 未结 1 1495
野的像风
野的像风 2020-12-06 06:44

I have some problems passing data from an activity to fragments in it. I searched around but didn\'t find an answer which suit my situation well. I have 2 fragment class nam

相关标签:
1条回答
  • 2020-12-06 07:48

    [EDIT] I've updated my answer to better respond to your question.

    You can also retrieve fragments by tag with getFragmentManager().findFragmentByTag("tag"). Be careful though, if the tab has not been viewed yet the fragment will not exist.

    CurrentFragment curFrag = (CurrentFragment)
        getFragmentManager().findFragmentByTag("current");
    if(curFrag == null) {
        // The user hasn't viewed this tab yet
    } else {
        // Here's your data is a custom function you wrote to receive data as a fragment
        curFrag.heresYourData(data)
    }
    

    If you want the fragment to pull the data from the activity have your activity implement an Interface defined by the fragment. In the onAttach(Activity activity) lifecycle function for fragments you get access to the activity that created the fragment so you can cast that activity as the Interface you defined and make function calls. To do that put the interface in your fragment like this (You can also make the interface its own file if you want to share the same interface among many fragments):

    public interface DataPullingInterface {
        public String getData();
    }
    

    Then implement the the interface in your activity like this:

    public class MyActivity extends Activity implements DataPullingInterface {
        // Your activity code here
        public String getData() {
            return "This is my data"
        }
    }
    

    Finally in your onAttach(Activity activity) method in CurrentFragment cast the activity you receive as the interface you created so you can call those functions.

    private DataPullingInterface mHostInterface;
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if(D) Log.d(TAG, "onAttach");
        try {
            mHostInterface = (DataPullingInterface) activity;
        } catch(ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DataPullingInterface");
        }
        String myData = mHostInterface.getData();           
    }
    
    0 讨论(0)
提交回复
热议问题