我有活动,其中包含viewpager,每个标签上都有一些片段。我想从片段中调用一些方法。我正在使用:
android.support.v4.app.Fragment;
我的代码: 主要活动:
public class ProfileActivity extends BaseTabsActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initTabs();
// call method here
}
}
public class BaseTabsActivity extends BaseActivity {
protected void initTabs() {
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(4);
mViewPager.setAdapter(new ProfileTabsAdapter(getSupportFragmentManager(), this));
}
}
ProfileTabsAdapter:
public class ProfileTabsAdapter extends FragmentPagerAdapter {
public ProfileTabsAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int index) {
switch (index) {
case 0:
return context.getResources().getString(R.string.string0);
case 1:
return context.getResources().getString(R.string.string1);
case 2:
return context.getResources().getString(R.string.string2);
case 3:
return context.getResources().getString(R.string.string3);
case 4:
return context.getResources().getString(R.string.string4);
}
return null;
}
}
片段:
public class Fragment0 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
return rootView;
}
public String doSomething() {
return "hi";
}
}
有什么想法吗?
答案 0 :(得分:0)
官方文档中对此进行了详细描述:https://developer.android.com/training/basics/fragments/communicating.html
为了您的方便,以下是代码的相关部分:
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
}
但请确保并阅读我在开头时链接的文档。