Toolbar In Android Studio

Ali Talha Çoban
2 min readJul 26, 2021

--

Hi everyone, in this wirting I will talk about Toolbar in Android Studio and how to use that.

What’s Toolbar ?

To briefly talk about the Toolbar, it is actually a ViewGroup that comes to Android with API 21 (Android Lollipop)
and is used instead of the ActionBar that comes to our project by default.

Why we use Toolbar?

Maybe you’re wondering that if ActionBar is available by default in project, then why we use Toolbar instead of ActionBar in our projects .
There are many reason for this. Firstly, you can set(color,shape,title on it,) toolbar more easily, also can set location in layout(top,bottom,right and left,middle).

How To Use In Android Studio ?

In order to use the Toolbar, we first need to disable the default ActionBar.For this you need to open themes file in values folder and turn ActionBar to NoActionBar there.

By doing so, we got rid of ActionBar that comes by default. Now we can add Toolbar in our page.
To make it,we go to XML layout file of activity we want to add Toolbar and then add the following to the XML file.

<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="@color/design_default_color_primary"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

?attr/actionBarSize is the attribute to gives heigh of the ActionBar to Toolbar.

Finally, we need to connect the activity and Toolbar we created

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Oluşturduğumuz Toolbar'ı id ile bağlıyoruz
Toolbar toolbar = findViewById(R.id.toolbar);

// Bunu yaparak da actionbar olarak artık oluşturdğumuz toolbarı kullancağımızı bildirmiş oluyoruz.
setSupportActionBar(toolbar);

// Başlık ve ve altbaşlığını düzenlemek
getSupportActionBar().setTitle("Toolbar Example");
getSupportActionBar().setSubtitle("Subtitle of Toolbar");

// Toolbar'a icon eklemek
getSupportActionBar().setIcon(R.drawable.menu_icon);

}
}

Yes now our Toolbar is complete.In code above I tried to talk about some of attributes of Toolbar,
otherwise there are several attributes for Toolbar available in Anroid Studio to set Toolbar.

Toolbar we created

In this writing I tried to briefly talk about Toolbar, I hope this writing helped you. Stay follow for writings like this.

contact : cobanalitalha@gmail.com

--

--

Ali Talha Çoban
Ali Talha Çoban

Written by Ali Talha Çoban

Backend Developer | Node.js | MongoDB | MySQL

No responses yet