【问题标题】:Toolbar layout doesn't match parent width工具栏布局与父宽度不匹配
【发布时间】:2017-04-03 19:29:36
【问题描述】:

我已经阅读了几个类似的主题,但仍然没有找到这个问题的答案。我有一个工具栏的自定义布局:

<android.support.design.widget.AppBarLayout    android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#99000000">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_transparent"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:fitsSystemWindows="true"
        android:minHeight="?attr/actionBarSize"
        app:theme="@style/MyToolbar">

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_centerInParent="true"
        android:id="@+id/toolbar_title" />

</RelativeLayout>

这是我的活动代码:

    toolbar = (Toolbar) findViewById(R.id.toolbar_transparent);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

我的工具栏仍然有左右填充并且没有填充父宽度。我尝试了各种解决方案。我的代码有什么问题? 问题是我需要我的工具栏是半透明的。这就是为什么我在布局 android:background="#99000000" 中使用这条线。我将它应用于整个布局,我的工具栏变得半透明,但它没有填充父级的宽度。但是,如果我将 android:background="#99000000" 这行应用到整个布局,而是应用到布局中的工具栏小部件,它会正确填充父级,但会失去透明度。这有帮助吗?

【问题讨论】:

标签: android android-layout android-actionbar android-toolbar


【解决方案1】:

如果填充是问题,您可以尝试设置contentInset 属性:

https://developer.android.com/reference/android/widget/Toolbar.html#attr_android:contentInsetStart

【讨论】:

    【解决方案2】:

    试试这个布局:

    半透明toolbar

        <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/general_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null">
    
        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="#99000000">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="Login"
                android:textSize="20sp" />
        </android.support.v7.widget.Toolbar>
    
    </android.support.design.widget.AppBarLayout>
    

    输出:

    【讨论】:

    • 感谢您的回答,但问题仍未解决:(
    • 左右内边距保持不变。我的布局也是半透明的,但我无法处理填充(
    最近更新 更多