BottomNavigationView+ViewPager+Fragment 男娘i 2022-05-16 01:08 190阅读 0赞 # BottomNavigationView+ViewPager+Fragment # package com.shop.pet; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView mTextMessage; private ViewPager mViewPager; private MenuItem mMenuItem; private BottomNavigationView navigation; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: mViewPager.setCurrentItem(0); return true; case R.id.navigation_pet: mViewPager.setCurrentItem(1); return true; case R.id.navigation_find: mViewPager.setCurrentItem(2); return true; case R.id.navigation_message: mViewPager.setCurrentItem(3); return true; case R.id.navigation_my: mViewPager.setCurrentItem(4); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mViewPager = (ViewPager) findViewById(R.id.viewpager); navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setLabelVisibilityMode(1); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); setupViewPager(mViewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(R.id.f_home, BaseFragment.newInstance(0)); adapter.addFragment(R.id.f_pet, BaseFragment.newInstance(1)); adapter.addFragment(R.id.f_find, BaseFragment.newInstance(2)); adapter.addFragment(R.id.f_message, BaseFragment.newInstance(3)); adapter.addFragment(R.id.f_my, BaseFragment.newInstance(4)); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (mMenuItem != null) { mMenuItem.setChecked(false); } else { navigation.getMenu().getItem(0).setChecked(false); } mMenuItem = navigation.getMenu().getItem(position); mMenuItem.setChecked(true); } @Override public void onPageScrollStateChanged(int state) { } }); } } ![这里写图片描述][70] 一些网友可能会遇到BottomNavigationView的Item项超过3时,不能完全显示文字,从代码中可以看到如下部分 private boolean isShifting(int labelVisibilityMode, int childCount) { return labelVisibilityMode == -1 ? childCount > 3 : labelVisibilityMode == 0; } 所以代码中将labelVisibilityMode设置掉即可。 [70]: /images/20220516/70076c0845fa43a3ae631e14d0a2d398.png
还没有评论,来说两句吧...