Issue
Is there a way to set a MaterialToolbar
as an Activity
's ActionBar
? Whenever I try to set mine, Android Studio keeps asking for a Toolbar
from the support library.
Required: Toolbar? - Found: MaterialToolbar
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"
android:id="@+id/myAppBarLayout">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/myCollapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|snap|exitUntilCollapsed">
<com.google.android.material.appbar.MaterialToolbar
android:id="@+id/myToolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetStartWithNavigation="0dp"
app:layout_collapseMode="pin" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
Kotlin
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.collapsingtoolbar_and_recyclerview)
val mCoordinatorLayout = findViewById<CoordinatorLayout>(R.id.myCoordinatorLayout)
val mCollapsingToolbarLayout = findViewById<CollapsingToolbarLayout>(R.id.myCollapsingToolbarLayout)
val mToolbar = findViewById<MaterialToolbar>(R.id.myToolbar)
// ...Do other stuff here
setActionBar(mCollapsingToolbarLayout)
mCollapsingToolbarLayout.title = "Hello, world!"
}
}
Solution
setActionBar()
requires a framework Toolbar
. MaterialToolbar
correctly extends the AndroidX Toolbar
, which means you must use AppCompatActivity
and setSupportActionBar()
and not Activity
and setActionBar()
.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.collapsingtoolbar_and_recyclerview)
//[...]
val toolbar = findViewById<MaterialToolbar>(R.id.myToolbar)
setSupportActionBar(toolbar)
// ...Do other stuff here
supportActionBar.title = "My MainActivity"
supportActionBar.setDisplayHomeAsUpEnabled(true)
}
}
Answered By - ianhanniballake
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.