Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have to create one Toolbar for each activity in my Android app?

I have this doubt about new Toolbar in Android.

I have to create one Toolbar for each activity in my app or there are a best practice to create one Toolbar for all activities?

I try create a Singleton inflating a layout and search a view ID to create a toolbar and return the same instance for all activities, but this don't work.

Can anybody help me? :S

like image 865
Daniel Filho Avatar asked Sep 25 '15 00:09

Daniel Filho


People also ask

What is the difference between a toolbar and an action bar?

An Action bar is traditionally a part of an Activity opaque window decor controlled by the framework but a Toolbar may be placed at any level of nesting within a view hierarchy. The toolbar provides more feature than ActionBar . A Toolbar may contain a combination of elements from start to end.

How do I get the activity toolbar?

if you are using custom toolbar or ActionBar and you want to get reference of your toolbar/action bar from Fragments then you need to first get instance of your Main Activity from Fragment's onCreateView Method like below. ImageView vRightBtn = activity. toolbar. findViewById(R.


2 Answers

Toolbar is just a view and you have to add it to your each Activity in which you want to show it.

One way is to just put it in a separate layout file and include in your Activity layout.

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    >

</android.support.v7.widget.Toolbar>

Now in your Activity layout where you want to add it just include like this:

<include
        android:id="@+id/toolbar"
        layout="@layout/toolbar"/>
like image 193
Sharj Avatar answered Feb 25 '23 18:02

Sharj


You can also extend Your activity class with AppCompatActivity instead of Activity

like image 34
mch.zawalski Avatar answered Feb 25 '23 18:02

mch.zawalski