[英]Custom Toggle Button: How to prevent text overlapping with icon
我正在尝试制作一个自定义切换按钮,其图标比原始内置按钮大得多。 我想实现以下目标:
*-------------------*
* *------------* *
* * * *
* * Icon * *
* * * *
* *------------* *
* *------------* *
* * Text * *
* *------------* *
*-------------------*
这是我的按钮:
<ToggleButton
android:id="@+id/tb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="18dp"
android:background="@drawable/custom_toggle_layer"
android:gravity="bottom | center_horizontal"
android:textAppearance="@style/CustomTBText"
android:textColor="@color/white"
android:textOff="@string/tb_off"
android:textOn="@string/tb_on" />
定制背景在drawable/custom_toggle_layer.xml
定义:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/custom_toggle_bg" />
<item android:id="@+android:id/toggle"
android:drawable="@drawable/custom_toggle_icon" />
</layer-list>
其中custom_toggle_bg
和custom_toggle_icon
都是选择器,并且工作正常。
问题是文本与图标的底部重叠。 文本与底部对齐,如果我将图标放大,则文本会正确粘贴到按钮的底部。
我首先尝试在切换按钮上设置填充,但这只是将文本在图标内向上移动了一点。
我试图独立于按钮设置文本样式,因此我定义了一种自定义样式:
<style name="CustomTBText">
<item name="android:textSize">14sp</item><!-- This works -->
<item name="android:textColor">@color/white</item><!-- This works -->
<item name="android:paddingTop">15dp</item><!-- This does not work -->
</style>
并尝试仅对文本设置顶部填充,但是该属性不起作用(样式中的其他属性可以正常工作)。
我怎样才能解决这个问题? 我可以通过设置按钮的文本为空并使用外部TextView进行破解,但如果可能的话,我想使用自定义的ToggleButton进行所有操作。
关于自定义切换按钮的大多数教程的作用是将图层列表设置为整个按钮的背景:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background"
android:drawable="@drawable/custom_toggle_bg" />
<item android:id="@+android:id/toggle"
android:drawable="@drawable/custom_toggle_icon" />
</layer-list>
这会导致文本出现问题(这也是大多数教程不显示文本的原因)。 因此,我要做的是将custom_toggle_bg
设置为背景,并将custom_toggle_icon
为drawableTop,现在可以使用了。 这是固定的按钮:
<ToggleButton
android:id="@+id/tb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="18dp"
android:background="@drawable/custom_toggle_bg"
android:drawableTop="@drawable/custom_toggle_icon"
android:gravity="bottom | center_horizontal"
android:textAppearance="@style/CustomTBText"
android:textColor="@color/white"
android:textOff="@string/tb_off"
android:textOn="@string/tb_on" />
您可以使用drawable的位置,例如drawableLeft,drawableTop,drawabeRight,drawableBottom和drawableStart,具体取决于您要查看的图标。
问候!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.