how to initialize(pass arguments) fragments for ac

2019-08-11 04:00发布

I followed http://developer.android.com/guide/topics/ui/actionbar.html#Tabs

It uses the following code to add Tab.

Tab tab = actionBar.newTab()
            .setText(R.string.artist)
            .setTabListener(new TabListener<ArtistFragment>(
                    this, "artist", ArtistFragment.class));
    actionBar.addTab(tab);

I want to supply argument to the fragment's constructor or call myInit(myVariableList) method on the fragment instance before showing the tab for the first time.

How can I do that?

1条回答
孤傲高冷的网名
2楼-- · 2019-08-11 04:26

You can use tab.setTag() to link an arbitrary object to the tab. If you can put myVariableList into a Bundle, you can achieve a simple solution by doing the following --

Tab tab = actionBar.newTab()
            .setText(R.string.artist)
            .setTabListener(new TabListener<ArtistFragment>(
                    this, "artist", ArtistFragment.class));
    tab.setTag(myVariableBundle);
    actionBar.addTab(tab);

Then, in your onTabSelected callback, send the Bundle when you instantiate your fragment --

mFragment = Fragment.instantiate(mActivity, mClass.getName(), (Bundle) tab.getTag());

You should then be able to access your Bundle during the fragment lifecycle using getArguments()

查看更多
登录 后发表回答