In Order to display action bar back button in Kotlin
there are 2 way to implement it
1. using the default Action Bar provided by Android
- Your activity must use a theme that has Action Bar
- eg: Theme.AppCompat.Light.DarkActionBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val actionBar = supportActionBar
actionBar!!.title = "your title"
actionBar.setDisplayHomeAsUpEnabled(true)
//actionBar.setDisplayHomeAsUpEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
2. Design your own Action Bar
- disable default Action Bar
- eg: Theme.AppCompat.Light.NoActionBar
- add layout to your activity.xml
<androidx.appcompat.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="16dp">
<TextView
android:id="@+id/main_toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Title"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(findViewById(R.id.main_toolbar))
}
<?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/main_action_toolbar"
android:icon="@drawable/ic_main_toolbar_item"
android:title="find"
android:layout_width="80dp"
android:layout_height="35dp"
app:actionLayout="@layout/toolbar_item"
app:showAsAction="always"/>
</menu>
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_toolbar_item, menu)
leftToolbarItems = menu!!.findItem(R.id.main_action_toolbar)
val actionView = leftToolbarItems.actionView
val badgeTextView = actionView.findViewById<TextView>(R.id.main_action_toolbar_badge)
badgeTextView.visibility = View.GONE
actionView.setOnClickListener {
println("click on tool bar")
}
return super.onCreateOptionsMenu(menu)
}