我有一个活动。当我单击按钮时,我想在 Fragment 中运行该方法。但它不起作用。我尝试了很多方法,但我无法让它工作。我的活动;public class MyActivity extends Activity {Button button;TabLayout tabLayout;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.myactivity_main); tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("First")); tabLayout.addTab(tabLayout.newTab().setText("Second")); viewPager= (CustomViewPager) findViewById(R.id.pager); final PagerAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); button = (Button)findViewById(R.id.button); button .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyFragment firstfragment = (MyFragment ) getFragmentManager().findFragmentByTag(“tab1”); firstfragment.MyMethod(); } }); }}我的片段适配器import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import com.webviewapp.Fragment.PromotionFragment;import com.webviewapp.Fragment.WebFragment;public class MyFragmentAdapter extends FragmentPagerAdapter {int tabCount;public MyFragmentAdapter(FragmentManager fm, int numberOfTabs) { super(fm); this.tabCount = numberOfTabs;}
2 回答
慕妹3146593
TA贡献1820条经验 获得超9个赞
如果你想从 FirstFragment 调用一个方法
FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().getFragments().get(0);
firstFragment.MyMethod();
如果你想从 SecondFragment 调用一个方法
SecondFragment secondFragment = (SecondFragment) getSupportFragmentManager().getFragments().get(1);
secondFragment.MyMethod();
索引 0 或 1 基于getItem您的适配器方法中的位置。
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment();
return tab2;
default:
return null;
}
}
那就试试吧。
添加回答
举报
0/150
提交
取消