从MainActivity的片段中调用函数

时间:2018-07-28 14:19:59

标签: android android-fragments android-activity methods tabs

修改
具有功能A1的片段A
片段B 功能B1
主要活动中的两个标签
tabA收到片段A
tabB收到片段B
我的问题是:从主要活动中调用函数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);
}
 }

2 个答案:

答案 0 :(得分:2)

根据您发布的代码,您可以像这样直接在“活动”中保存片段的实例

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

然后在您活动的任何地方只要使用它们即可

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

您还可以保存适配器并使用它来访问片段,如

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

并在“活动”调用中访问它们

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

答案 1 :(得分:1)

您可以使用broadcastreceiver

片段A

public static final String BROADCAST_ACTION = "BROADCAST_ACTION";

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null &&
                intent.getAction().equals(BROADCAST_ACTION)) {
                //Call your function A
        }
    }
};

@Override
public void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(
            context).registerReceiver(broadcastReceiver, new IntentFilter(BROADCAST_ACTION));
}

@Override
public void onStop() {
    super.onStop();
    LocalBroadcastManager.getInstance(context).unregisterReceiver(broadcastReceiver);
}

在您要调用片段方法的活动中,发送广播:

Intent intent = new Intent(FragmentA.BROADCAST_ACTION);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);