我有ViewPager
活动。 ViewPager
也有一个TabLayout
,带有3个选项卡:FragmentA
,FragmentB
和FragmentC
,每个对应于要在ViewPager
中显示的3个页面之一。虽然我会有一个按钮,但在FragmentB
里面。我现在需要能够点击这个按钮并创建一个新的片段,FragmentD
,这将超过FragmentB
。这个新的片段需要有一个带有后退箭头的操作栏,以便返回到FragmentB
。在所有这些过程中,标签仍应显示FragmentB
是活动标签。我已经研究过嵌套的碎片,但是我无法完成它的工作。我也尝试从我的片段创建一个对viewpager acitivty的引用,并调用getItem方法和我的新片段的位置,但这不起作用。这是我现在的代码。这是一项活动,创建ViewPager
。在ViewPager
3片段内创建和TabLayout
还创建:ViewPager - 在片段页面中创建一个新片段
public class MyActivity extends AppCompatActivity {
ViewPager viewPager;
PagerAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Get the ViewPager and set it's PagerAdapter so that it can display items
viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MyActivity.this);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(3);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "FragmentA", "FragmentB", "FragmentC", };
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MyFragmentA();
case 1:
return new MyFragmentB(); //Inside of fragment B I will have a button. If that button is clicked this fragment needs to be replaced with a new fragment temporarliy, FRAGMENTD, which will have an anctionbar to be able to go back to fragment B. The tabs should show that the user is technically still in FragmentB tab.
case 2:
return new MyFragmentC();
}
return null;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MyActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
//This populates your Fragment reference array:
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
fragments[position] = createdFragment;
return createdFragment;
}
}
}
负载
FragmentB
在FragmentD
您的片段返回新实例每次只是将其存储在列表和返回它与适当的位置 – Nas@Nas对不起,我不确定你的意思?所以我创建了3个片段,例如新的MyFragmentC()。你是说那么在这里创建一个第四个片段,并将其放入case 3(如情况3):return MyFragmentD()?如果是的话,我怎么从MyFragmentB中获得这个新的片段,并将它制作一个“孩子”,然后我可以导航回来? – user2924127