我有两个片段,我在页面的底部做了一个布局,如下所示
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.alsongdunstan.thefaithapp.ui.utils.NonSwipeableViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/tabs"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
app:tabGravity="fill"
app:tabMode="fixed" />
</RelativeLayout>
然后我创建了一个活动类,我将其用作活动,从中为视图寻呼机创建适配器并填充视图寻呼机
private class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
这是我从
填充视图寻呼机的地方 private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adding filter list fragment
filtersListFragment = new FiltersListFragment();
filtersListFragment.setListener(this);
// adding edit image fragment
editImageFragment = new EditImageFragment();
editImageFragment.setListener(this);
adapter.addFragment(filtersListFragment, getString(R.string.tab_filters));
adapter.addFragment(editImageFragment, getString(R.string.tab_edit));
viewPager.setAdapter(adapter);
}
这就是我的应用在完成上述所有操作后的样子。
答案 0 :(得分:1)
通过将ViewGroup
(通常为FrameLayout
)替换为您想要的片段实例,将片段添加到活动中。
在您的活动布局XML中:
<RelativeLayout
...>
<FrameLayout
android:id="@+id/placeholder_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
现在在您的活动的Java代码中:
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.placeholder_fragment, new MyFragment())
.commit();