iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
Mobile Development

Kotlin 實踐 Material Design 懶人包系列 第 25

Day25 延續前實戰新增 Modal navigation drawer 、MaterialSwitch實作

  • 分享至 

  • xImage
  •  

延續之前Day19延續前實戰新增Bottom Sheets、Full-screen dialogs實作後繼續新增,這次將實現Day20~Day24文章介紹MDC的 Navigation drawerMaterialSwitch的實作。

介紹的內容:

https://ithelp.ithome.com.tw/upload/images/20221008/201444694PkYAUiHkx.png

  • 使用 IDE版本 : Android Studio Chipmunk | 2021.2.1 Canary 7
  • 使用 MDC Android Components
  • 實作介紹 (提供完整程式碼)
    • Add Modal navigation drawer
    • Add MaterialSwitch

Add Modal navigation drawer

在Module層的build.Gradle的dependencies中新增implementation 'androidx.drawerlayout:drawerlayout:1.1.1'

https://ithelp.ithome.com.tw/upload/images/20221008/20144469NcricLlks3.png

  1. 調整原本頁面的Layout最外層新增DrawerLayout

  2. 新增NavigationView

    <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.fragment.ProductCardsFragment">
    
        <androidx.coordinatorlayout.widget.CoordinatorLayout
           ... >
    				<!--AppBarLayout-->
    					...
    				<!--Toggle Button:Single-select、Cards-->
    					...
    				<!--BottomAppBar-->
    					...
    				<!--FloatingActionButton-->
    					...
    
        </androidx.coordinatorlayout.widget.CoordinatorLayout>
    
        <!--NavigationView-->
        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigationView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/header_navigation_drawer"
            app:menu="@menu/item_navigation_drawer" />
    
    </androidx.drawerlayout.widget.DrawerLayout>
    
  3. Navigation drawer 打開,新增binding?.drawerLayout?.open()在原本的TopAppBar的setNavigationOnClickListener

    Navigation drawer 關閉,新增binding?.drawerLayout?.close()navigationView?.setNavigationItemSelectedListener

    binding?.topAppBar?.setNavigationOnClickListener {
        // 新增 Navigation drawer
        binding?.drawerLayout?.open()
    }
    
    binding?.navigationView?.setNavigationItemSelectedListener { menuItem ->
                // menu點處理選定
                when (menuItem.itemId) {
                    R.id.notification -> { //通知
                        if (activity != null) {
                            binding?.drawerLayout?.close()
                            (activity as NavigationHost).navigateTo(NotificationSetFragment(), false)
                        }
                    }
                    R.id.privacySet -> { // 隱私設定
                        Toast.makeText(context, "隱私設定", Toast.LENGTH_SHORT).show()
                    }
                    R.id.account -> { // 用戶
                        // 使用者資料點擊開啟Full-screen dialogs
                        if (activity != null) {
                            binding?.drawerLayout?.close()
                            requireActivity().supportFragmentManager.let {
                                FullScreenDialogFragment().show(it, "")
                            }
                        }
                    }
                    R.id.about -> { // 關於
                        Toast.makeText(context, "關於", Toast.LENGTH_SHORT).show()
                    }
                    R.id.logout -> { // 登出
                        Toast.makeText(context, "登出", Toast.LENGTH_SHORT).show()
                    }
                }
                true
            }
    

Add MaterialSwitch

設定頁面上新增Switch的狀態更改

https://ithelp.ithome.com.tw/upload/images/20221008/20144469tzfaWaJ1Il.png

navigationView點擊「通知」開啟頁面

binding?.navigationView?.setNavigationItemSelectedListener { menuItem ->
   // menu點處理選定
   when (menuItem.itemId) {
       R.id.notification -> { //通知
            if (activity != null) {
                 binding?.drawerLayout?.close()
                 (activity as NavigationHost).navigateTo(NotificationSetFragment(), false)
            }
   }
			....
            true
}

推播通知開關,設定開關thumb有更換icon

binding?.switchPause?.setOnCheckedChangeListener{ _ , isChecked->
    if (isChecked) {
       // 開啟時
       binding?.switchPause?.thumbIconDrawable=
       AppCompatResources.getDrawable(requireContext(), R.drawable.ic_check)
    } else {
       // 關閉時
       binding?.switchPause?.thumbIconDrawable=
       AppCompatResources.getDrawable(requireContext(), R.drawable.ic_close)
     }
}

電子郵件通知

binding?.switchEmail?.setOnCheckedChangeListener { _, isChecked ->
   if (isChecked) {
      Toast.makeText(requireContext(), "點擊電子郵件通知", Toast.LENGTH_SHORT).show()
   }
}

設定頁面 layout.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_back"
        style="@style/Widget.Material3.Button.IconButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:icon="@drawable/ic_back"
        app:iconTint="@color/dark_gray"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通知"
        android:textSize="18dp"
        app:layout_constraintBottom_toBottomOf="@id/btn_back"
        app:layout_constraintStart_toEndOf="@id/btn_back"
        app:layout_constraintTop_toTopOf="@id/btn_back" />

    <com.google.android.material.divider.MaterialDivider
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        app:dividerColor="@color/gray"
        app:layout_constraintTop_toBottomOf="@id/tv_title" />

    <!--推播通知-->
    <TextView
        android:id="@+id/tv_notification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="推播通知"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider" />

    <com.google.android.material.materialswitch.MaterialSwitch
        android:id="@+id/switch_pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="20dp"
        android:text="全部暫停"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_notification"
        app:thumbIcon="@drawable/ic_close" />

    <com.google.android.material.divider.MaterialDivider
        android:id="@+id/divider2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        app:dividerColor="@color/gray"
        app:dividerInsetEnd="10dp"
        app:dividerInsetStart="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/switch_pause" />

    <!--其他通知類型-->
    <TextView
        android:id="@+id/tv_notification_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="其他通知類型"
        android:textSize="18dp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/divider2" />

    <com.google.android.material.materialswitch.MaterialSwitch
        android:id="@+id/switch_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="20dp"
        android:checked="true"
        android:text="電子郵件通知"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_notification_other" />

</androidx.constraintlayout.widget.ConstraintLayout>

NotificationSetFragment.kt 程式碼

class NotificationSetFragment: Fragment() {

    private var _binding: FragmentNotificationSettingBinding? = null
    private val binding  get() = _binding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentNotificationSettingBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()
    }

    private fun initView() {
        binding?.btnBack?.setOnClickListener {
            (activity as NavigationHost).navigateTo(ProductCardsFragment(), false)
        }


        // 推播通知
        binding?.switchPause?.setOnCheckedChangeListener{ _ , isChecked->
            if (isChecked) {
                // 開啟時
                binding?.switchPause?.thumbIconDrawable=
                    AppCompatResources.getDrawable(requireContext(), R.drawable.ic_check)
            } else {
                // 關閉時
                binding?.switchPause?.thumbIconDrawable=
                    AppCompatResources.getDrawable(requireContext(), R.drawable.ic_close)
            }
        }

        // 電子郵件通知
        binding?.switchEmail?.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                Toast.makeText(requireContext(), "點擊電子郵件通知", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

以上是這次的實作內容 歡迎下載程式碼參考
感謝您看到這邊 /images/emoticon/emoticon08.gif

參考資料:
Day20 使用M3的Navigation drawer
Day23 使用M3MaterialSwitch


上一篇
Day24 使用M3的Sliders
下一篇
Day26 使用M3的Progress Indicators
系列文
Kotlin 實踐 Material Design 懶人包30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言