커스텀 액션바 만들기(toolbar)

sumi Yoo·2022년 11월 23일
0

먼저, .NoActionBar로 변경해주어야 한다.(이미 적용되어 있는걸 해제해줘야 한다.)

theme.xml

<resources>
    <!-- Base application theme. -->
    <style name="Theme.Promise" parent="Theme.MaterialComponents.DayNight.NoActionBar">
</resources>

activity_main.xml

맨 위에 Toolbar 배치

<?xml version="1.0" encoding="utf-8"?>
<layout 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"
    tools:context=".ui.promisesetting.PromiseDetailActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintVertical_bias="0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

MainActivity

override fun onCreate(savedInstanceState: Bundle?) {
 setSupportActionBar(binding.toolbar)
        supportActionBar?.apply {
            setDisplayShowCustomEnabled(true)
            setDisplayShowTitleEnabled(false)
            setDisplayHomeAsUpEnabled(true)
        }
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_toolbar, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.edit -> {
                val intent = Intent(this, PromiseSettingActivity::class.java).putExtra(
                    PROMISE_KEY,
                    promiseDetailViewModel.promiseUiState.value
                )
                startActivity(intent)
                finish()
            }
            R.id.delete -> {
                deletePromise()
            }
        }
        return super.onOptionsItemSelected(item)
    }
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/edit"
        android:enabled="true"
        android:title="편집"/>

    <item
        android:id="@+id/delete"
        android:enabled="true"
        android:title="삭제"/>

</menu>

결과

0개의 댓글