我有一个带有两个标签的viewpager,每个标签都有一个片段。我如何发送额外的意图字符串来说FragmentMathematics()?这并不像使用putExtra创建一个intent然后调用strartActivity()那样直截了当。
这是我的简单课程。
public class StartActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private String check;
private PagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout404);
tabLayout.addTab(tabLayout.newTab().setText("Mathematics"));
tabLayout.addTab(tabLayout.newTab().setText("Physics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
Intent intent = getIntent();
check = intent.getStringExtra("SELECTVALUE");
if("Mathematics".equalsIgnoreCase(check)){
selectPage(1);
} else {
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter
(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) {
}
});
}
void selectPage(int pageIndex){
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
谢谢!
答案 0 :(得分:1)
使用Bundle将数据传递给片段。
Bundle bundle = new Bundle();
bundle.putString("edttext", "Your Value");
// set Fragmentclass Arguments
FragmentMathematics fragobj = new FragmentMathematics();
fragobj.setArguments(bundle);
并在片段OnCreate()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String strtext = getArguments().getString("edttext");
}