Android bottom navigation bar implementation

  • Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The bottom navigation bar is very widely used. Here are a few ways to do it today.

Fragment + TextView implementation

A previous blog post on Fragments used Fragment + ImageView to implement a bottom navigation bar click example, just replace ImageView with TextView. See this blog for an overview of Android Fragment and how to use it

This way we’re going to reset the state of all our TextViews every time we click, and then we’re going to select the TextView that we clicked on

RadioGroup + ViewPager

We just overwrite the RadioGroup onCheckedChange, check the checkid to see which RadioButton is clicked on, and set the listener on the ViewPager to synchronize the bottom navigation bar with the ViewPager.

Operation effect:

  1. Create four new layout files

Here I put the code for a layout file, and all the others are the same.


      
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:src="@drawable/tx4"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I"
        android:textSize="50sp"
        android:textColor="#ff0000"
        android:layout_gravity="center" />

</LinearLayout>
Copy the code
  1. Write the XML where we replace the bottom navigation ICONS, and import our ICONS with and without a different color selected. I’ll just give you oneme_drawable.xmlAn example of

Sets selected and unselected images respectively


      
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/me_select"/>
    <item android:state_checked="false" android:drawable="@drawable/me_normal"/>
</selector>
Copy the code
  1. Write the activity_main.xml layout

      
<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="com.mq.bottomtoobar2.MainActivity">

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/rg_tab"/>

    <RadioGroup
        android:id="@+id/rg_tab"
        android:layout_width="fill_parent"
        android:layout_height="55dp"
        android:gravity="center_vertical"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_msg"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:checked="true"
            android:drawableTop="@drawable/msg_drawable"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="Information" />
        <RadioButton
            android:id="@+id/rb_people"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:drawableTop="@drawable/people_drawable"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="Contact" />

        <RadioButton
            android:id="@+id/rb_find"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:drawableTop="@drawable/find_drawable"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="Discovered" />
        <RadioButton
            android:id="@+id/rb_me"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:drawableTop="@drawable/me_drawable"
            android:gravity="center"
            android:paddingLeft="0dp"
            android:text="我" />
    </RadioGroup>
</RelativeLayout>
Copy the code

Note: Android: Button =”@null” property can remove the edge of the ring.

  1. Write the MainActivity code
public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private RadioGroup mRadioGroup;
    private RadioButton tab1,tab2,tab3,tab4;  // Four radio buttons
    private List<View> mViews;   // Store the view
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();// Initialize the data
        // Listen on the radio button, select and unselect
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_msg:
                        mViewPager.setCurrentItem(0);
                        break;
                    case R.id.rb_people:
                        mViewPager.setCurrentItem(1);
                        break;
                    case R.id.rb_find:
                        mViewPager.setCurrentItem(2);
                        break;
                    case R.id.rb_me:
                        mViewPager.setCurrentItem(3);
                        break; }}}); }private void initView(a) {
        // Initialize the controller
        mViewPager=findViewById(R.id.viewpager);
        mRadioGroup=findViewById(R.id.rg_tab);
        tab1=findViewById(R.id.rb_msg);
        tab2=findViewById(R.id.rb_people);
        tab3=findViewById(R.id.rb_find);
        tab4=findViewById(R.id.rb_me);

        mViews=new ArrayList<View>();// Add a view
        mViews.add(LayoutInflater.from(this).inflate(R.layout.msg,null));
        mViews.add(LayoutInflater.from(this).inflate(R.layout.people,null));
        mViews.add(LayoutInflater.from(this).inflate(R.layout.find,null));
        mViews.add(LayoutInflater.from(this).inflate(R.layout.me,null));

        mViewPager.setAdapter(new MyViewPagerAdapter());// Set up an adapter
        // Listen on viewPager to keep tabs and bottom ICONS sliding together
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Override   // Let the following ICONS change as the viewPager slides
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        tab1.setChecked(true);
                        tab2.setChecked(false);
                        tab3.setChecked(false);
                        tab4.setChecked(false);
                        break;
                    case 1:
                        tab1.setChecked(false);
                        tab2.setChecked(true);
                        tab3.setChecked(false);
                        tab4.setChecked(false);
                        break;
                    case 2:
                        tab1.setChecked(false);
                        tab2.setChecked(false);
                        tab3.setChecked(true);
                        tab4.setChecked(false);
                        break;
                    case 3:
                        tab1.setChecked(false);
                        tab2.setChecked(false);
                        tab3.setChecked(false);
                        tab4.setChecked(true);
                        break; }}@Override
            public void onPageScrollStateChanged(int state) {}}); }/ / ViewPager adapter
    private class MyViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount(a) {
            return mViews.size();
        }


        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view==object;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(mViews.get(position));
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(mViews.get(position));
            returnmViews.get(position); }}}Copy the code

BottomNavigationView+ViewPager+fragment implementation

This is a View provided by Google specifically for Bottom Navigation. You just need to select “Bottom Navigation Activity” when creating a new Activity.

Operation effect:

The Tab of BottomNavigationView is added via menu. Use relatively simple, you do not need to define their own control, only need to modify the menu file and callback method he defined for you here but more introduction, we can go to see the code inside.

4, TabLayout+fragment+viewPager implementation

It’s easy to think of a table layout for the bottom navigation bar, and then just TAB by TAB to switch the viewPager.

This is probably the most common implementation.

Operation effect:

  1. Import toolkits in build.gradle:
Implementation 'com. Android. Support: design: 27.1.1' implementation 'com. Android. Support: support - v4:27.1.1'Copy the code
  1. Write the activity2_main.xml layout file

      
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/tablayout"/>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tablayout"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:layout_height="50dp">
</com.google.android.material.tabs.TabLayout>
</RelativeLayout>
Copy the code
  1. Write four fragments and the layout

Here I give you one Fragment, and all the others are the same.

public class me extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_me, container, false); }}Copy the code

Layout code

<FrameLayout 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"
    tools:context="com.mq.bottomtoobar3.me">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/tx4"/>

</FrameLayout>
Copy the code
  1. Write an adapter that MyAdapt inherits from FragmentPagerAdapter
public class MyAdapt extends FragmentPagerAdapter {

    private List<Fragment> mFragments;
    private List<String> mtitle;

    public MyAdapt(@NonNull FragmentManager fm, List<Fragment> mFragments,List<String> mtitle) {
        super(fm);
        this.mFragments=mFragments;
        this.mtitle=mtitle;
    }

    @NonNull
    @Override  // Returns the specified fragment
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override  // Return the number of fragments
    public int getCount(a) {
        return mFragments.size();
    }

    @Nullable
    @Override  // Get the paging title
    public CharSequence getPageTitle(int position) {
        returnmtitle.get(position); }}Copy the code
  1. Write MainActivity2 code
public class MainActivity2 extends AppCompatActivity {

    private List<Fragment> mFragments;   // Store the view
    private ViewPager viewPager;
    private TabLayout mTabLayout;
    private List<String> mtitle;  // Store the bottom title
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2_main);

        initView();
    }

    private void initView(a) {
        mTabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.viewpager);

        mFragments=new ArrayList<>();
        mFragments.add(new msg());
        mFragments.add(new people());
        mFragments.add(new find());
        mFragments.add(new me());

        mtitle=new ArrayList<String>();
        mtitle.add("Information");
        mtitle.add("Contact");
        mtitle.add("Discovered");
        mtitle.add("I");
        
        // Instantiate the adapter
        MyAdapt adapt = new MyAdapt(getSupportFragmentManager(), mFragments, mtitle);
        viewPager.setAdapter(adapt);

        mTabLayout.setupWithViewPager(viewPager);// Set a viewpager for the TAB
        / / viewpager listening in
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Override  / / selected
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        Toast.makeText(MainActivity2.this."This is the message.", Toast.LENGTH_SHORT).show();
                        break;

                    case 1:
                        Toast.makeText(MainActivity2.this."This is the contact.", Toast.LENGTH_SHORT).show();
                        break;

                    case 2:
                        Toast.makeText(MainActivity2.this."This is discovery.", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(MainActivity2.this."This is mine.", Toast.LENGTH_SHORT).show();
                        break; }}@Override   // //state has three states, 0 means nothing is done, 1 is sliding, 2 is sliding finished
            public void onPageScrollStateChanged(int state) {}}); }}Copy the code

summary

The bottom navigation bar can be implemented in many different ways, mainly considering layout allocation. The main content above shows what you want to implement, and the bottom navigation below shows what you want to implement, as long as it can be combined and established to listen to the consistency of the function of the bottom navigation bar.

Similarly, the bottom navigation bar can be implemented as the top navigation bar

That’s all for today’s sharing!