android 底部菜单-- BottomNavigationView + fragment 实现

杭永安
2023-12-01

 新建三个fragment 。 

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/menu1"
        android:icon="@drawable/ic_list"
        android:title="111"/>

    <item
        android:id="@+id/menu2"
        android:icon="@drawable/ic_person_add"
        android:title="222"/>

    <item
        android:id="@+id/menu3"
        android:icon="@drawable/ic_find"
        android:title="333"/>


</menu>

 

package com.e.bottomnavigationtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.os.Bundle;
import android.view.MenuItem;

import com.e.bottomnavigationtest.ui.login.LoginFragment111;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
        getSupportFragmentManager().beginTransaction().replace(R.id.fram1, new BlankFragment1()).commit();

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment fragment = null;

                switch (item.getItemId()){
                    case R.id.menu1:fragment = new BlankFragment1();
                        break;
                    case R.id.menu2:fragment = new BlankFragment2();
                        break;
                    case R.id.menu3:fragment = new LoginFragment111();
                        break;
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.fram1, fragment).commit();

                return false;
            }
        });
    }
}

 

 类似资料: