先說說iOS上的三大Controller: ViewController, NavigationController, TabBarController
在Android上的對應是ViewController 對應 Activity
NavigationController呢,因為人家天生最左下方就是有系統的返回鍵,感覺不是非常必要
而TabBarController就是今天要講的主題:BottomNavigationView
而講到BottomNavigationView呢,就不得不講到Fragment
Fragment根據官方的定義:
Fragment 代表一種行為或 Activity 中的一部分使用者介面。
您可以合併單一 Activity 中的多個片段,藉此建置 多窗格 UI 以及在多個 Activity 中重複使用片段。
您可以將片段想成是 Activity 的模組化區段,片段擁有自己的生命週期、接收自己的輸入事件,
而且您可以在 Activity 執行時新增或移除片段 (有點像是您可以在不同 Activity 中重複使用的「子 Activity」)。
而我自己簡單的想法就是:因為Android不像iOS可以ViewController addChildViewController,所以他們發明了可以加在Activity上的東西:Fragment
所以iOS上常見的ContainerViewController模式到的Android上就要請Fragment出馬了
例如官網提供的下面這張圖,不正是我們的SplitViewController嗎?
另外Fragment也有所謂的生命週期,
請見官方提供的另兩張圖 |-|
|-|
強行置入工商分隔線
如果您是愛寫MarkDown的工程師(不是工程師也沒關係)
那麼您千萬不能錯過HackMD這個服務
光是多~圖拖拉直接上傳並生成連結這個功能就夠好用的(我鐵人賽都靠它)
更不用說即時預覽/整合VSCode/簡報模式...等等千千萬萬的功能
請立即試用~

 

 
    <item android:title="red"
        android:icon="@color/red"
        android:id="@+id/bottom_navi_red"/>
    <item android:title="yellow"
        android:icon="@color/red"
        android:id="@+id/bottom_navi_yellow" />
    <item android:title="green"
        android:icon="@color/red"
        android:id="@+id/bottom_navi_green" />
 
 
貼在上面也可以XDDD),然後愛多高就多高XDDDDFrameLayout(記不記得我們第六堂課說過FrameLayout的主要用途就是拿來顯示Fragment?)    private void changeFragment(FragmentType index)
    {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        switch (index)
        {
            case red:
                fragmentTransaction.replace(R.id.frame_layout_for_fragment,new RedFragment());
                break;
            case yellow:
                fragmentTransaction.replace(R.id.frame_layout_for_fragment,new YellowFragment());
                break;
            case green:
                fragmentTransaction.replace(R.id.frame_layout_for_fragment,new GreenFragment());
                break;
        }
        fragmentTransaction.commit();
    }
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
            {
                switch (menuItem.getItemId())
                {
                    case R.id.bottom_navi_red:
                        changeFragment(FragmentType.red);
                        return true;
                    case R.id.bottom_navi_yellow:
                        changeFragment(FragmentType.yellow);
                        return true;
                    case R.id.bottom_navi_green:
                        changeFragment(FragmentType.green);
                        return true;
                }
                return false;
            }
        });
 
 
 
可以去 https://github.com/mark33699/IDLA 看一下順便給顆⭐️
如果你喜歡我的影片別忘了按讚分享加訂閱,開啟紅色的小鈴鐺,我們明天見~