Use Toolbar across all activities (Android)

时间秒杀一切 提交于 2019-12-02 17:59:16

I found the solution, I forgot to include the toolbar in the rest of the activities layout files. So I was calling a toolbar that didn't exist in that activity's layout.

I only had it included in the main activity so that's why it worked there and crashed at the rest.

For beginners, this mean the following code must exist in every layout xml file you wish the toolbar to work in:

<include layout="@layout/app_bar"/>

Note that "app_bar" is just the name I called my toolbar with, yours can be different.

Good luck.

you can create a layout with follow code that contain toolbar

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    tools:context="com.tejariapp.myapplicationtester1.MainActivity">


    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

</android.support.design.widget.CoordinatorLayout>

pay attention to height value ,if you don't set it wrap_content value you can see that other elements gone below toolbar and then in each layout that you want to have toolbar ,simply you can write this

<include layout="@layout/toolabar" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!