Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

android - FragmentTabHost & Fragments - How do I pass data between tabs?

I have a MainActivity (FragmentActivity) that has a FragmentTabHost.

public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("classA").setIndicator("Class A"),
            ClassA.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("classB").setIndicator("Class B"),
            ClassB.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("classC").setIndicator("Class C"),
            ClassC.class, null);
    }
}

ClassA, ClassB and ClassC are all Fragments (android.support.v4.app.Fragment).

I need to pass data (and call methods) on the Fragments. How can I get a reference of each of the Fragments, like this:

ClassA mClassAFragment = ???;

I've tried using getSupportFragmentManager().findFragmentByTag() and I've also tried exploring the capabilities of mTabHost. Nothing can get them.

Can you suggest a way to do this or suggest an alternative approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OP here. To solve this problem I have overloaded the onAttachFragment method in my FragmentActivity:

public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
    super.onAttachFragment(fragment);

    if (fragment.getClass() == ClassA.class) {
        ClassA mClassAFragment = (ClassA)fragment
            ...
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...