Pregunta

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?

And i tried used this...

Bundle arguments = new Bundle();
arguments.putString("some id string", "your data");
YourFragment fragment = new YourFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.fragmentid, fragment).commit();

but i dont know how can use this R.id.fragmentid if my add tabs is well:

mTabHost.addTab(mTabHost.newTabSpec("classA").setIndicator("Class A"),
                ClassA.class, null);

Anyone help me?

¿Fue útil?

Solución

Define the Fragments in your Activity as public. Then in each Fragment you also reference the Activity.

In your Activity:

public ClassAFragment aFragment;
...
// during initialization:
aFragment = new ClassAFragment();
// or you get it from your TabHost
FragmentManager fm = getFragmentManager();
aFragment = fm.findFragmentByTag("ClassA");
aFragment.mActivity = this;
// same with B and C

In your Fragments:

public MainActivity mActivity;
...
// in Fragment C
String newText = mActivity.aFragment.editText.getText().toString() + mActivity.bFragment.editText.getText().toString();
textView.setText(newText); 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top