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

ぐ巨炮叔叔 提交于 2019-11-29 11:11:44

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
            ...
        }
    }
}

You can get your fragment like this:

YourFragment frag = (YourFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.fragmentid));

To send data to a fragment you can follow this approach, creating a new transaction and sending the data through a bundle.

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();

This can be accomplished by the 3rd argument of android.support.v4.app.FragmentTabHost.addTab(TabSpec, Class, Bundle args), then the args can be retrieved via android.support.v4.app.Fragment.getArguments()

public class Tab1Fragment extends BaseFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // do something with the arguments
    Log.i("DEBUG", "" + getArguments());
    // ...
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!