【发布时间】:2015-04-09 20:18:36
【问题描述】:
我希望文本以Button 为中心。但是每当我将android:drawableLeft xml 属性添加到Button 时,它都会偏移文本。我该如何解决?
我设法解决它的唯一方法是在android:drawablePadding 中设置一个负数:
但我正在寻找一种更清洁的解决方案来实现它。
【问题讨论】:
标签: android button textview drawable
我希望文本以Button 为中心。但是每当我将android:drawableLeft xml 属性添加到Button 时,它都会偏移文本。我该如何解决?
我设法解决它的唯一方法是在android:drawablePadding 中设置一个负数:
但我正在寻找一种更清洁的解决方案来实现它。
【问题讨论】:
标签: android button textview drawable
不幸的是,这是 Button 行为,我同意你的观点,负填充是一种肮脏的 hack,所以我将提出另外两个对我来说听起来不那么脏的 hack,因为它们依赖于预期的行为(负填充虽然有效,但不是设计使然):
android:paddingRight 设置为可绘制对象的大小【讨论】:
所以我最终选择了取其轻巧的方法,那就是将可绘制对象和文本放在 RelativeLayout 中:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Button.ButtonGray"
android:id="@+id/share_button">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_share"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_centerInParent="true"
style="@style/TextNormalWeight"
android:text="@string/post_share"/>
</RelativeLayout>
RelativeLayout 然后接收点击事件并表现得像一个按钮。
【讨论】:
android:gravity="center_vertical"
【讨论】:
gravity 已经是center(不仅仅是center_vertical)。
不幸的是,没有干净的方法可以做到这一点。一种相当直接的方法是在按钮的另一侧设置一个大小相同的透明 ColorDrawable。
val drawableSize = button.height // adjust this as desired of course
realDrawable.setBounds(0, 0, drawableSize, drawableSize)
val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
setBounds(0, 0, drawableSize, drawableSize)
}
button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)
【讨论】:
它适用于:
android:gravity="center"
【讨论】: