如何更改芯片视图(Chip view)的字体?

10

我想要更改设计支持库中Chip视图的字体。在查看其源代码后,我发现它通过Paint直接在ChipDrawable中绘制文本,并且我找不到任何公共方法来更改字体。我应该如何尝试更改Chip视图的字体?请帮忙。谢谢。

3个回答

29

虽然有些晚了,但我将发布我的解决方案,以防仍有人感兴趣。

首先创建一个使用您自定义字体的字体系列XML。

<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <font app:fontStyle="normal" app:fontWeight="400" app:font="@font/my_custom_font"/>
</font-family>
然后在您的样式xml中添加一个芯片样式,使用您的字体系列:
<style name="chipText" parent="TextAppearance.MaterialComponents.Chip">
    <item name="android:textSize">14sp</item>
    <item name="android:fontFamily">@font/my_font_family</item>
</style>

然后,在xml中创建芯片视图时,设置textAppearance属性:

android:textAppearance="@style/chipText"

2
它对我不起作用。我以编程方式加载芯片,当它首次加载默认字体,然后是我的字体时,芯片视图会闪烁。对于许多芯片来说,虽然最终使用了正确的字体,但看起来并不好看。有人有类似的问题吗? - Nikola Samardzija
谢谢,它能工作,不过直接在芯片中设置字体不起作用。 - Jenya Kirmiza

3
使用这个。
chip.typeface = Typeface.create(ResourcesCompat.getFont(this,R.font.segoe_ui),Typeface.NORMAL)

1
你的解决方案可以正常工作,但在 TextInputLayout 内部仍存在一些问题(字体未更改)。注意:屏幕旋转后自定义字体发生了变化,原因不明。使用以下实现即可解决问题:implementation "com.google.android.material:material:1.3.0-alpha01"。
   <com.google.android.material.textfield.TextInputLayout
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_gravity="center"
        android:textAppearance="@style/chipText"
        android:hint="Text Field">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Text"
            android:textAppearance="@style/chipText"/>

    </com.google.android.material.textfield.TextInputLayout>

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