Android Development: use TabLayout+Fragment to realize the bottom bar switching function

thinking

First of all, you need to know the basic usage of Fragment. Here, you can refer to Chapter 4 of the second edition of the first line of Android code by Guo Lin. If you want to realize four columns (homepage, mall, message, me), you need the following documents

  • 4 fragmented xml files + main xml files + Tab self-made xml files, 6 xml files in total
  • 4 Fragment files
  • 1 main Activity file and 1 tool class DataGenerator file.
  • 8 small icons for tab s. You can modify the drawable name in the DataGenerator file by clicking four before and after each, or only four above.

Step 1: overall page xml

First of all, understand that Fragment is to be inserted into the FrameLayout in XML, so you can create a new button tab.xml and set this to start XML (set in the BottomTab file below).
Button tab.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/home_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >
    </FrameLayout>

    <View android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:alpha="0.6"
        android:background="@android:color/darker_gray"
        />
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/bottom_tab_layout"
        android:layout_width="match_parent"
        app:tabIndicatorHeight="0dp"
        app:tabSelectedTextColor="@android:color/black"
        app:tabTextColor="@android:color/darker_gray"
        android:layout_height="50dp"

        app:tabRippleColor="@null"

        app:tabMaxWidth="0dp"
        app:tabGravity="fill">

    </com.google.android.material.tabs.TabLayout>

</LinearLayout>

Step 2: fragment, the top page except the bottom column

Four of the Fragment files are inherited from Fragment, and then the four xml files above are inflate d, in the following form:
(replace the fragment ﹣ home ﹣ page with the corresponding xml file name.)
fragment_home_page.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="home page" />
</LinearLayout>

HomePageFragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        return view;
    }
}

In this way, four xml files and four Fragment files are generated.

Start writing main Activity:ButtomTab

Before you start, implement the DataGrenerate tool class to help ButtomTab achieve better.
This tool class is to prepare the fragments and the elements in the fragments first (where the getTabView function is used to customize the Tab)

public class DataGenerator {

    public static final int []mTabRes = new int[]{R.drawable.outline_fastfood_black_18,R.drawable.outline_shopping_cart_black_18,R.drawable.outline_textsms_black_18,R.drawable.outline_person_black_18};
    public static final int []mTabResPressed = new int[]{R.drawable.baseline_fastfood_black_18,R.drawable.baseline_shopping_cart_black_18,R.drawable.baseline_textsms_black_18,R.drawable.baseline_person_black_18};
    public static final String []mTabTitle = new String[]{"home page","Shopping Mall","news","I"};

    public static Fragment[] getFragments(){
        Fragment fragments[] = new Fragment[4];
        fragments[0] = new HomePageFragment();
        fragments[1] = new ShopPageFragment();
        fragments[2] = new MessagePageFragment();
        fragments[3] = new PersonPageFragment();
        return fragments;
    }

// Get the view view of position and initialize the elements in it for init
    public static View getTabView(Context context, int position){
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_tab,null);
        ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_content_image);
        tabIcon.setImageResource(DataGenerator.mTabRes[position]);
        TextView tabText = (TextView) view.findViewById(R.id.tab_content_text);
        tabText.setText(mTabTitle[position]);
        return view;
    }
}

The ButtomTab file follows:

public class ButtomTab extends AppCompatActivity {
    private TabLayout tab_layout;
    private Fragment[] framensts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buttom_tab);

        framensts = DataGenerator.getFragments();
        initView();
    }

    private void initView() {
        tab_layout = (TabLayout) findViewById(R.id.bottom_tab_layout);


        //Set up a listener
        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                onTabItemSelected(tab.getPosition());

                // After Tab is selected, change the status of each Tab
                for (int i = 0; i < tab_layout.getTabCount(); i++) {
                    View view = tab_layout.getTabAt(i).getCustomView();
                    ImageView icon = (ImageView) view.findViewById(R.id.tab_content_image);
                    TextView text = (TextView) view.findViewById(R.id.tab_content_text);

                    if (i == tab.getPosition()) { // Check status, change font color and picture, background not implemented
//                        view.setBackgroundColor(Color.parseColor("#a9a9a9"));
                        icon.setImageResource(DataGenerator.mTabResPressed[i]);
                        text.setTextColor(getResources().getColor(android.R.color.black));
                    } else {// Unchecked status
//                        view.setBackgroundColor(Color.parseColor("#FFFFFF"));
                        icon.setImageResource(DataGenerator.mTabRes[i]);
                        text.setTextColor(getResources().getColor(android.R.color.darker_gray));
                    }
                }
            }


            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        // Provide a customized layout to add tabs. Note that the loading page here needs to be set after the Listener is set, otherwise the first click event will be invalid
        for(int i=0;i<4;i++){
            tab_layout.addTab(tab_layout.newTab().setCustomView(DataGenerator.getTabView(this,i)));
        }

        //Enter home page by default (after loading page)
        tab_layout.getTabAt(0).select();
    }

    private void onTabItemSelected(int position){
        Fragment frag = null;
        switch (position){
            case 0:
                frag = framensts[0];
                break;
            case 1:
                frag = framensts[1];
                break;

            case 2:
                frag = framensts[2];
                break;
            case 3:
                frag = framensts[3];
                break;
        }
        //Replace fragment
        if(frag!=null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.home_container,frag).commit();
        }
    }
}

The main body code and architecture of this article come from Android bottom navigation bar (bottom Tab) best practices gold diggers Thank you.

33 original articles published, 67 praised, 70000 visitors+
Private letter follow

Tags: Android xml Fragment encoding

Posted on Sun, 09 Feb 2020 02:19:28 -0500 by Bobby_Jo