【问题标题】:Button text not centered when textSize exceeds maxHeight当 textSize 超过 maxHeight 时,按钮文本不居中
【发布时间】:2019-01-03 22:15:46
【问题描述】:

我正在尝试将按钮内的某些文本垂直居中,但是当 textSize 超过按钮的高度时,文本会与顶部对齐,就像 android:gravity="top" 而不是 android:gravity="center "

我通过添加 android:includeFontPadding="false" 和 android:paddingTop="0dp" 稍微改进了结果,但文本没有居中。我希望文本垂直居中,因此在按钮上方和下方被剪裁。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:includeFontPadding="false"
    android:maxHeight="40dp"
    android:paddingTop="0dp"
    android:text="Button"
    android:textSize="60dp" />
</android.support.constraint.ConstraintLayout>

这是布局的截图...

https://imgur.com/gallery/8I5IRZn

【问题讨论】:

    标签: android xml android-layout


    【解决方案1】:

    你试过删除 maxHeight 吗?

    您的布局中的问题是您的文本大于 40dp,但 40dp 是 maxHeight。 所以换行内容最多只能达到 40dp。

    【讨论】:

    • 问题要求剪切文本,只在顶部和底部,而不是单独在底部。
    • 确实如此。我认为负边距会做到这一点。
    【解决方案2】:

    尝试使用负填充或边距来向上移动文本。

    【讨论】:

    • 添加正或负上边距根本不会改变文本的位置。是否有其他设置与此效果冲突/否定?需要注意的是,最终用户将决定按钮的高度和文本的高度,因此要使此解决方案起作用,我需要一个公式来从按钮高度和文本高度值中推导出负边距值跨度>
    • 这可能是 android 的限制(尽管可能是有意的)。一个可能的解决方案可能是制作两个覆盖文本但位于按钮内部的空块以切断字符。一个用于上边距,一个用于下边距,并将按钮的边距和填充设置为 0。然后块的大小可能只是基于按钮高度的某个百分比。
    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 2021-06-14
    • 2012-01-02
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2011-11-23
    • 2017-03-17
    相关资源
    最近更新 更多