[Kotlin]Drawerlayout – 1.메인화면 부분(Main Screen Part)

더 친절한 코틀린 앱프로그래밍 책에 있는 코드 입니다.
This is code from the Friendlier Kotlin App Programming book

이 코드는 뷰바인딩을 사용하지 않았습니다.
This code does not use view binding.

Test : compileSdk = 35 targetSdk = 35

1.Directory & Files

2.MainActivity.kt

package com.example.drawerex

import android.os.Bundle
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.google.android.material.navigation.NavigationView

class MainActivity : AppCompatActivity() {

    enum class FragmentItem{
        ITEM1,ITEM2,ITEM3
    }

    lateinit var fragment:Fragment
    lateinit var toolbar:Toolbar
    lateinit var drawerLayout:DrawerLayout
    lateinit var navigationView: NavigationView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.drawerLayout)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)

        toolbar = findViewById(R.id.toolbar)
        drawerLayout = findViewById(R.id.drawerLayout)
        navigationView = findViewById(R.id.navigationView)

        //toolbar excute
        toolbar.title="첫번째 화면First Screen"
        setSupportActionBar(toolbar)

        //DrawerLayout excute
        val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close)
        drawerLayout.addDrawerListener(toggle)
        toggle.syncState()

        // Fragment1 excute
        fragment = Fragment1()
        supportFragmentManager.beginTransaction().replace(R.id.container,fragment).commit()

        navigationView.setNavigationItemSelectedListener {
            when(it.itemId){
                R.id.item1 -> {
                    showToast("첫번째 선택됨First Screen Selected")
                    onFragmentSelected(FragmentItem.ITEM1,null)
                }
                R.id.item2 -> {
                    showToast("두번째 선택됨Second Screen Selected")
                    onFragmentSelected(FragmentItem.ITEM2,null)
                }
                R.id.item3 -> {
                    showToast("세번째 선택됨Third Screen Selected")
                    onFragmentSelected(FragmentItem.ITEM3,null)
                }
            }
            drawerLayout.closeDrawer(GravityCompat.START)
            return@setNavigationItemSelectedListener true
        }
    }



/*
        // deprecated
        override fun onBackPressed() {
            if(layoutDrawer.isDrawerOpen(GravityCompat.START)) {
                layoutDrawer.closeDrawers()
            }
            else {
                super.onBackPressed()
            }
*/

    fun onFragmentSelected(item:FragmentItem,bundle: Bundle?){
        var fragment:Fragment

        when(item){
            FragmentItem.ITEM1 ->{
                toolbar.title="첫 번째 화면First Screen"
                fragment = Fragment1()
            }
            FragmentItem.ITEM2 ->{
                toolbar.title="두 번쨰 화면Second Screen"
                fragment = Fragment2()
            }
            FragmentItem.ITEM3 ->{
                toolbar.title="세 번쨰 화면Third Screen"
                fragment = Fragment3()
            }
        }
        supportFragmentManager.beginTransaction().replace(R.id.container,fragment).commit()
    }

    private val onBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if(drawerLayout.isDrawerOpen(GravityCompat.START)){
                drawerLayout.closeDrawers()
            }
            else {
                finish()
            }
        }
    }

    fun showToast(message:String?){
        Toast.makeText(this,message,Toast.LENGTH_LONG).show()
    }

}

3.activity_main.xml

-xml design

-xml code

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="30dp"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </com.google.android.material.appbar.AppBarLayout>

        <FrameLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"></FrameLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/nav_menu" />
</androidx.drawerlayout.widget.DrawerLayout>

Leave a Reply

Your email address will not be published. Required fields are marked *