gpt4 book ai didi

java - 将显式 Intent 从 ViewPagerAdapter 传递给 fragment

转载 作者:行者123 更新时间:2023-12-02 11:41:36 25 4
gpt4 key购买 nike

我有一个带有两个选项卡的viewpager,每个选项卡都有一个 fragment 。我如何发送额外的 Intent 字符串来表示 FragmentMathematics()?这并不像使用 putExtra 创建 Intent 然后调用 strartActivity() 那样简单。

这是我的简单类(class)。

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

谢谢!

最佳答案

使用Bundle将数据传递给fragment。

Bundle bundle = new Bundle();
bundle.putString("edttext", "Your Value");
// set Fragmentclass Arguments
FragmentMathematics fragobj = new FragmentMathematics();
fragobj.setArguments(bundle);

并在 fragment OnCreate()中

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String strtext = getArguments().getString("edttext");

}

关于java - 将显式 Intent 从 ViewPagerAdapter 传递给 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48512822/

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