gpt4 book ai didi

android - 从 MainActivity 的 fragment 中调用函数

转载 作者:行者123 更新时间:2023-11-29 16:39:23 25 4
gpt4 key购买 nike

编辑
fragment A 具有功能 A1
fragment B 具有功能 B1
主要 Activity 中的两个标签
tabA 得到 fragment A
tabB 得到 fragment B
我的问题是:从主要 Activity 调用函数 A1

 //here i create taps and fragment into viewpaper

private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(),"ONE");
adapter.addFragment(new TwoFragment(),"TWO");
viewPager.setAdapter(adapter);
}



class ViewPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}

public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}

@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment,String tittle){
mFragmentList.add(fragment);
mFragmentTitleList.add(tittle);
}
}

最佳答案

根据您发布的代码,您可以像这样将 fragment 的实例直接保存在您的 Activity 中

private OneFragment f1;
private TwoFragment f2;

private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
f1 = new OneFragment();
f2 = new TwoFragment();
adapter.addFragment(f1,"ONE");
adapter.addFragment(f2,"TWO");
viewPager.setAdapter(adapter);
}

然后你想在你的 Activity 中的任何地方调用它们就可以了

f1.myMethod();
f2.myMethod();

您也可以只保存您的适配器并使用它来访问 fragment ,如

private ViewPagerAdapter adapter;

private void setupViewPager(ViewPager viewPager){
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(),"ONE");
adapter.addFragment(new TwoFragment(),"TWO");
viewPager.setAdapter(adapter);
}

并在 Activity 调用中访问它们

OneFragment f1 = (OneFragment)adapter.getItem(0);
TwoFragment f2 = (TwoFragment)adapter.getItem(1);

关于android - 从 MainActivity 的 fragment 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51572212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com