【问题标题】:Custom ToolBar not there自定义工具栏不存在
【发布时间】:2018-08-07 15:46:50
【问题描述】:

我决定制作自己的工具栏

所以我删除了常规工具栏:

<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


【解决方案1】:

在您的&lt;include&gt; 标记中,您已将工具栏的ID 设置为@+id/custombar,但您正在使用R.id.toolbar 进行查找。将该行更改为:

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

【讨论】:

    【解决方案2】:

    没有清楚地了解您的问题,但我仍然会发布我如何编写代码来设置自定义工具栏。

    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);
    

    而且它工作正常。

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

    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);
    

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多