0

So i'm trying to design a toolbar for an app in XML but facing difficulties. So the code i have so far is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#cacaca"

    />

how do i insert a toolbar so i could use to add features to it? Should it be done using XML? or is there another way to do this?

asdwe
  • 23
  • 5

2 Answers2

1

You have to do it by xml way.. First of all you have to create in a separate xml file like this

Toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:background="@color/primary"
     />

then you have to use this in your layout like this

 <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

After that you have to define it in your activity

import android.support.v7.widget.Toolbar;

private Toolbar nToolbar;

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_add_subject);
        this.setToolBar();
}
 private void setToolBar() {
        nToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(nToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Title");
    }
Saurabh Vardani
  • 1,821
  • 2
  • 18
  • 33
0

Adding on the answer to "saurabh gupta" If you want to define a custom layout with the help of toolbar implement this way:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:local="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="@color/primary">
        <!-- Your own implementation of layout -->
        // .. 
        <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:background="#cacaca"
        />
        .. //
</android.support.v7.widget.Toolbar>
Haris Aftab
  • 259
  • 1
  • 9