首先,我是 Android 开发的新手,非常感谢您的帮助。
我在 android studio 中有一个选项卡式活动,我有一个 FloatingActionButton 来在选项卡式活动的每个片段中添加一个项目。然后此按钮调用一个新的 Activty,我想将选项卡编号传递给新活动,以便我可以将其存储在数据库中。
如何获取生成新活动的选项卡编号?
下面是代码:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", position_fragment);
startActivity(startNewPostActivity);
}
});
}
为了获得这个位置,我做了以下事情:设置 position_fragment = position; 但是这会返回错误的选项卡编号。
公共类 SectionsPagerAdapter 扩展 FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
position_fragment = position; // not good
return PlaceholderFragment.newInstance(position);
}
@Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
}