Android 如何在片段中使用viewpager和TableLayout?
我需要我的应用程序有底部栏导航和可滑动标签。所以我需要viewpager在嵌套在底部导航使用的每个片段中的片段之间交换。如何执行此操作?首先,创建一个包含ViewPager和TableLayout的片段,如下所示Android 如何在片段中使用viewpager和TableLayout?,android,android-viewpager,fragment,Android,Android Viewpager,Fragment,我需要我的应用程序有底部栏导航和可滑动标签。所以我需要viewpager在嵌套在底部导航使用的每个片段中的片段之间交换。如何执行此操作?首先,创建一个包含ViewPager和TableLayout的片段,如下所示 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layo
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".FragmentThatHasViewPagerAndTabLayout">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
在包含ViewPager和TableLayout的片段中编写代码,您只需像平常一样编写它(比如有一个FragmentPagerAdapter等)它与您在activity中所做的相同(如果您已经这样做了),只是在差异上,这是您传递的片段
getChildFragmentManager()
,而不是getSupportFragmentManager())
到您的fragmentPagerAdapter
构造函数
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@color/colorPrimary"
app:itemIconTint="#FFF"
app:itemTextColor="#FFF"
app:menu="@menu/menu_bottom_navigation"/>
</LinearLayout>
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
//Change fragment when select another item in BottomNavigation
}
}
getFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentThatHasViewPagerAndTabLayout(), "TAG_TO_REUSE_FRAGMENT_AFTER_CONFIG_CHANGES").commit();
}