如何在固定大小的芯片中居中文本?(针对Android平台)

14

我有一个宽度为100dp的芯片,但文本没有居中显示,我该如何使文本居中。

我使用androidx和material库,我尝试使用android:textAlignment="center"android:gravity="center",但都没有起作用

<com.google.android.material.chip.Chip
    android:id="@+id/chip"
    style="@style/Widget.MaterialComponents.Chip.Choice"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:text="7:00" />

我有这个

芯片

我想要这个

输入图片描述


请问您能否发布一下您目前所完成的截图? - San Mo
是的,我更新了帖子。 - Jefferson Rojas
1
我认为这是不可能的。使用android:gravity="center",你应该在logcat中看到W/Chip: Chip text must be vertically center and start aligned - Gabriele Mariotti
4个回答

24

刚才我遇到了同样的问题,我通过设置一个芯片属性来解决它:android:textAlignment="center"。我测试了你的示例,它也可以正常工作,这里是我测试的代码:

<FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <com.google.android.material.chip.Chip
            android:id="@+id/chip"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="7:00"
            android:textAlignment="center"/>
</FrameLayout>

请确保在代码中不要设置或更改芯片的文本对齐方式。


chip.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); 如果你想以编程的方式实现它。 - Zee

2
简短回答:
芯片不应该像你尝试使用它们的方式那样使用。它们应该包裹你的内容。因此,没有一种干净的方法来将文本居中对齐。 不过有一个变通方法,你可以使用Chip_textEndPaddingChip_textStartPadding属性,但可能会有点尴尬。
我真的不知道你想要实现什么,我的意思是,你的目的是什么?这是一个按钮吗?它只是用来显示一些文本吗? 请描述这个功能,或者至少其中的一部分。
无论如何:
根据material design guidelines 芯片允许用户输入信息、进行选择、过滤内容或触发操作。芯片应以多个交互元素的组形式动态出现。与按钮不同,按钮应该是一致和熟悉的呼叫到行动,一个用户期望在同一区域出现相同的行动。

你的功能与此有关吗?

如果您需要可点击的圆形组件,您可以简单地使用材料按钮

有一个类似的问题在GitHub上被问到。


1

像其他人所说,您可以使用textAlignment...但我想告诉您,如果您正在使用自定义字体,它不会完美地垂直对齐。 您可以在这里检查进行解释。

所以我会创建一个继承自芯片样式的自定义样式,并设置字体填充以便像这样使用:

 <style name="customStyle" parent="@style/Widget.MaterialComponents.Chip.Choice">
    <item name="chipBackgroundColor">@color/white</item>

   ******* <item name="android:includeFontPadding">true</item> *************
  </style>

然后,对于文本外观,您可以创建另一个样式:
<style name="CustomChipTextAppearance" parent="TextAppearance.MaterialComponents.Chip">
    <item name="android:fontFamily">?attr/myFont</item>
    <item name="android:textAlignment">center</item>
  </style>

不要忘记在XML中强制使用桥梁主题:

    <com.google.android.material.chip.Chip xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      style="@style/customStyle"
      ****  android:theme="@style/Theme.MaterialComponents.Bridge" ****
***** android:textAppearance="@style/CustomChipTextAppearance"  *******
      app:chipMinHeight="38dp"
      android:layout_height="wrap_content"
      android:layout_width="wrap_content"
      app:chipStrokeWidth="2dp" 
      app:rippleColor="@android:color/transparent"
      tools:chipText="my chip" />

0
使用isTextAlignmentResolved,例如chipname.isTextAlignmentResolved()可以以编程方式完成此操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接