實作 Bottom Navigation View === ```java= public class MainActivity extends AppCompatActivity { private BottomNavigationView navView; private NavigationBarView.OnItemSelectedListener navListenr = new NavigationBarView.OnItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { item.setChecked(true); Fragment fragment = null; switch (item.getItemId()) { case R.id.navigation_home: fragment = new HomeFragment(); switchFragment(fragment); setTitle(R.string.title_home); break; case R.id.navigation_dashboard: fragment = new DashboardFragment(); switchFragment(fragment); setTitle(R.string.title_dashboard); break; case R.id.navigation_notifications: fragment = new NotificationsFragment(); switchFragment(fragment); setTitle(R.string.title_notifications); break; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initBottomNav(); initBody(); } private void initBottomNav() { navView = findViewById(R.id.nav_view); navView.setOnItemSelectedListener(navListenr); } private void initBody() { MenuItem homeItem = navView.getMenu().findItem(R.id.navigation_home); navListenr.onNavigationItemSelected(homeItem); } private void switchFragment(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.framelay, fragment); fragmentTransaction.commit(); } } ``` ## Ref. 傳統方法(需自定監聽器切換畫面) [How to implement BottomNavigationView with Fragments in Android Studio](https://www.youtube.com/watch?v=UMZZHHJ37bo) 傳統方法(不需自定監聽器) [BottomNavigationView with Navigation Component - Android Studio Tutorial](https://www.youtube.com/watch?v=Chso6xrJ6aU) ###### tags: `Bottom Navigation View`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up