自定义工具栏不在那里

问题描述 投票:0回答:2

我已决定制作自己的工具栏

所以我删除了常规的ToolBar:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="false"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar> //removetollbar

并制作我自己的工具栏

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

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

然后我包括在主xml中

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

</include>

并在我设置的代码中:

_CustomToolBar = (android.support.v7.widget.Toolbar) 
findViewById(R.id.custombar);
setSupportActionBar(_CustomToolBar);
android.support.v7.widget.Toolbar _CustomToolBar;

现在当应用程序运行自定义工具栏时不存在

请帮忙。

java android android-layout material-design android-toolbar
2个回答
1
投票

在你的<include>标签中,你已经将工具栏的id设置为@+id/custombar,但是你正在使用R.id.toolbar查找它。将该行更改为:

_CustomToolBar = (android.support.v7.widget.Toolbar) findViewById(R.id.custombar);

0
投票

没有清楚地得到你的问题,但我仍然会发布如何设置自定义工具栏的代码。

1)我的Manifest有NoActionBar主题删除默认工具栏。

2)我的custom_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="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="5dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

3)方式我将它包含在我的main.xml中

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

4)我的Java代码 -

// In onCreate method
android.support.v7.widget.Toolbar _CustomToolBar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(_CustomToolBar);

它运作正常。

enter image description here

那么我们的代码之间有什么不同。

1)给你的自定义工具栏正确id android:id="@+id/customToolbar"而不是给你include。 2)为自定义工具栏指定高度和背景颜色,以便正确显示

android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"

3)而不是将include id链接到工具栏,链接你的custom toolbar id

findViewById(R.id.customToolbar);
© www.soinside.com 2019 - 2024. All rights reserved.