You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Toolbar中Button的android:layout_weight属性失效问题求助

解决Toolbar中Button的layout_weight失效问题

嘿,我太懂这种困惑了!之前我也踩过这个Toolbar的坑,这就给你讲明白问题出在哪,以及怎么搞定它:

问题根源

你可能误以为Toolbar是个LinearLayout,但实际上Toolbar的内部布局逻辑和LinearLayout完全不同,它的子View默认使用的是Toolbar.LayoutParams,而非LinearLayout的LayoutParams。这就导致你设置的android:layout_weight根本不被识别,哪怕把layout_width设为0dp也没用——因为Toolbar压根不处理这个属性。

完美解决方案

最直接有效的办法是在Toolbar内部嵌套一个横向的LinearLayout,把你的两个Button放在这个LinearLayout里,这样就能利用LinearLayout的权重分配机制正常工作了。

修改后的布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:theme="@style/Base.Animation.AppCompat.Dialog">

    <android.support.v7.widget.Toolbar 
        android:id="@+id/toolbar" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:background="@color/colorAccent" 
        android:minHeight="?attr/actionBarSize" 
        android:theme="?attr/actionBarTheme">

        <!-- 嵌套横向LinearLayout承载Button,实现权重分配 -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2">

            <Button 
                android:id="@+id/button2" 
                android:layout_width="0dp" 
                android:layout_height="wrap_content" 
                android:layout_weight="1" 
                android:text="Button" />

            <Button 
                android:id="@+id/button3" 
                android:layout_width="0dp" 
                android:layout_height="wrap_content" 
                android:layout_weight="1" 
                android:text="Button" />
        </LinearLayout>

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

    <ProgressBar 
        android:id="@+id/progressBar" 
        style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal" 
        android:layout_width="match_parent" 
        android:layout_height="10dp" 
        android:indeterminateOnly="true" 
        android:progress="?android:attr/scrollbarDefaultDelayBeforeFade" />

    <android.support.v7.widget.RecyclerView 
        android:id="@+id/dd" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" />
</LinearLayout>

额外说明

如果你是想实现类似ActionBar的左右按钮效果,也可以考虑通过Toolbar的menu菜单来添加按钮,但如果需要自定义样式的Button,嵌套LinearLayout的方式会更灵活,完全能满足你的需求。

内容的提问来源于stack exchange,提问作者Vipme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:02:18