Мне нужна помощь для объединения ViewPager и BottomNavigationView.Но когда я провожу по экрану, как ViewPager работает, фрагмент становится сложен с другим фрагментом.Как это исправить?
Сложенный фрагмент
На обычном фрагменте до считывания
Вот мой код:
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private BottomNavigationView mBottomNavigation;
private ViewPager viewPager;
private ViewPagerAdapter mViewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
mBottomNavigation = findViewById(R.id.buttom_navigation);
mBottomNavigation.setOnNavigationItemSelectedListener(this);
viewPager = findViewById(R.id.view_pager);
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mViewPagerAdapter);
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container_frame_layout, fragment);
ft.commit();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.menu_home:
fragment = new HomeFragment();
break;
case R.id.menu_favorite:
fragment = new FavoriteFragment();
break;
case R.id.menu_account:
fragment = new AccountFragment();
break;
}
return loadFragment(fragment);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/container_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/buttom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:layout_alignParentBottom="true"
app:itemIconTint="#ffff"
app:itemTextColor="#ffff"
app:menu="@menu/item_menu"/>
</RelativeLayout>
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeFragment();
case 1:
return new FavoriteFragment();
case 2:
return new AccountFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
Заранее спасибо!