我想在tabsadapter中处理一个片段,这是我的Activity中的静态类。问题是如何在onTabSelected中获得getfragmentbytag?
从onCreate我有这个代码:
Tab tab1 = actionBar.newTab().setText("ABOUT");
tabsAdapter.addTab(tab1, PoiAboutFragment.class, null);
我的标签适配器类如下,没有问题。
public static class TabsAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
private Object gridTag;
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager,
ActionBar actionBar) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = actionBar;
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
if(clss.equals(GridFragment.class))
gridTag = tab.getTag();
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(),
info.args);
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
Log.i(TAG, "onTabSelected has been called");
if(tag.equals(gridTag))
Log.i(TAG, "gridtab has been called");
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
问题是我想在oncreate方法和tabsAdapter中处理我的一个片段,但我既没有片段标签也没有片段ID。我怎样才能从我的Activity中处理他们的方法?
答案 0 :(得分:1)
FragmentPagerAdapter source的makeFragmentName
方法显示使用以下标记创建片段:
"android:switcher:" + viewId + ":" + id
其中viewId是ViewPager的id,即使用
activity.getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + pager.getId() + ":0"
获取第一个片段。
答案 1 :(得分:0)
我找到了我在这个网站android-er.blogasppot
中寻找的答案