ToolBar
A Toolbar widget is a customizable app bar placed at the top of an activity or fragment and contains various UI elements such as a title, navigation icon, menu items, and actions. It was introduced as a replacement for the older ActionBar, providing more flexibility and customization options.
Some of the main features include:- Toolbar is more flexible then ActionBar.
- It looks modern and follows new material design.
- Define it and place it just like any other widget anywhere in the parent layout.
- Any widget can be placed inside toolbar.
- Multiple toolbars can be defined.
- An application may choose to designate a Toolbar as the action bar for an Activity using the setActionBar() method.
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
class MainActivity : AppCompatActivity() {
private lateinit var toolbar: Toolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
// Customize the toolbar as needed
supportActionBar?.apply {
title = "My Toolbar"
// Additional customization options
}
}
}
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"
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="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:title="Example Toolbar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<!-- Rest of layout -- >
</androidx.constraintlayout.widget.ConstraintLayout>