我有一个活动。当我单击按钮时,我想在 Fragment 中运行该方法。但它不起作用。我尝试了很多方法,但我无法让它工作。
我的活动;
public class MyActivity extends Activity {
Button button;
TabLayout tabLayout;
@Override
protected 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;
}
慕妹3146593
相关分类