MaterialButtonToggleGroup中多行文本按钮偏移问题求助
大家好,我现在碰到一个MaterialButtonToggleGroup的布局问题,想请各位帮忙看看怎么解决:
我在使用MaterialButtonToggleGroup搭配MaterialButton做切换组时,遇到了布局对齐的问题——部分按钮需要显示两行文本,但只要按钮里的文本超过一行,这个按钮就会往下偏移,比其他单行文本的按钮位置更低(比如我布局里最后一个按钮因为是两行文本,就明显比其他按钮靠下)。
先贴一下我的布局代码:
<GridLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/linearLayout2" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:columnCount="1" android:measureWithLargestChild="false" android:orientation="horizontal"> <com.google.android.material.button.MaterialButtonToggleGroup android:id="@+id/gateToggleGroup" android:layout_width="wrap_content" android:layout_height="100dp" android:layout_gravity="center_horizontal" android:theme="@style/ThemeOverlay.MaterialComponents" android:layout_marginLeft="16sp" android:layout_marginTop="10sp" android:layout_marginRight="16sp"> <com.google.android.material.button.MaterialButton style="?attr/materialButtonOutlinedStyle" android:id="@+id/toggle1" android:layout_width="wrap_content" android:layout_height="70dp" android:text="Vhod 1x" android:textSize="16sp" /> <com.google.android.material.button.MaterialButton style="?attr/materialButtonOutlinedStyle" android:id="@+id/toggle2" android:layout_width="wrap_content" android:layout_height="70dp" android:text="Izhod" android:textSize="16sp" /> <com.google.android.material.button.MaterialButton style="?attr/materialButtonOutlinedStyle" android:id="@+id/toggle3" android:layout_width="wrap_content" android:layout_height="70dp" android:text="Vhod" android:textSize="16sp" /> <com.google.android.material.button.MaterialButton style="?attr/materialButtonOutlinedStyle" android:id="@+id/toggle4" android:layout_width="wrap_content" android:layout_height="70dp" android:text="Izhod 1x" android:textSize="16sp" /> </com.google.android.material.button.MaterialButtonToggleGroup> </GridLayout>
我已经试过这些方法,但都没完美解决:
- 一开始我在XML里给按钮设置
maxLines属性完全没用,后来了解到MaterialButton会强制把这个值覆盖为1,所以改成在代码里动态给所有按钮设置maxLines = 2:
var button : MaterialButton = findViewById(R.id.toggle1) button.maxLines = 2 button = findViewById(R.id.toggle2) button.maxLines = 2 button = findViewById(R.id.toggle3) button.maxLines = 2 button = findViewById(R.id.toggle4) button.maxLines = 2
- 尝试过手动给按钮设置margin、固定按钮高度,都没能解决多行按钮偏移的问题;
- 试过把按钮的
lineHeight设为0sp,偏移的问题倒是解决了,但文本会被挤在一起,完全没法正常显示。
想请教各位,有没有什么办法能让多行文本正常换行显示,同时保证ToggleGroup里所有按钮都能对齐,不会出现偏移的情况?
内容来源于stack exchange
相关产品推荐
相关产品推荐

