๋ง MaterialToolbar ์ผ ๋ ๋จธ์ ๊ณ ๋ฏผ ์๋ ๋ค๋ฅธ ์ฌ๋๋ค ๋ค ์ฐ๋ ๊ฒ์ฒ๋ผ ์ผ๋๋ฐ ์ ์๋ฎฌ๋ ์ดํฐ๊ฐ ์ ๋์๊ฐ๋๋ฐ
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var toolbar: MaterialToolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
toolbar = findViewById(R.id.toolbar)
setToolbarListener()
}
...
}
toolbar = findViewById(R.id.toolbar) ์ด ๋ผ์ธ๋ง ์ฐ๋ฉด ์๋ฎฌ๋ ์ดํฐ๊ฐ ๋จนํต์ด ๋ผ์ ๋ฐ์ธ๋ฉํ๋ ๊ณผ์ ์์ ๋ถ๋ช ํ ์ฌ๊ธฐ์ ๋ฌธ์ ๊ฐ ์์ ๊ฑฐ๋ผ๊ณ ์๊ฐํ๊ณ ์ดํ์ ์ฌ๊ธฐ๋ง ๋ฏ์ด๋ณด๊ณ ์์๋๋ฐ ๋ฌธ์ ๋ ๋ค๋ฅธ ๊ณณ์ ์์๋ค
์ค์ ์์ธ์ ํด๋ฐ์ ํด๋ฐ๋ฅผ includeํ ๋ ์ด์์์์ ๋๊ฐ์ id๋ฅผ ์ค๋ณต์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ์ด์๋ค
toolbar ๋ผ๋ ์์ด๋๋ฅผ ๊ฐ์ง ๊ฐ์ฒด๊ฐ ๋ ๊ฐ๊ฐ ์์ผ๋ ์ด๋ค ๊ฑธ ์ฐพ์์ ๋ฐ์ธ๋ฉํด์ผ ํ ์ง ๋ชฐ๋ผ์ cannot be cast ์๋ ๊ฒ ๊ฐ๋ค
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.appbar.AppBarLayout 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="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:menu="@menu/menu_toolbar"
app:title="@string/app_name"
style="@style/Widget.MaterialComponents.Toolbar.Primary"/>
</com.google.android.material.appbar.AppBarLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar"/>
...
</androidx.constraintlayout.widget.ConstraintLayout>
๋ณ๊ฒฝ ํ
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="@+id/included_toolbar"
layout="@layout/toolbar"/>
...
</androidx.constraintlayout.widget.ConstraintLayout>
์ค๋ณต๋์ง ์๊ฒ ์์ด๋๋ฅผ ๋ณ๊ฒฝํด์ฃผ๊ณ ์คํ์ํค๋ ์ ์์ ์ผ๋ก ์๋ํ๋ค