自定义文本字体和颜色的Spinner

10

我想在下拉菜单Spinner中使用自定义字体和颜色。但我不能直接在<spinner/>标签中修改它们。

这是我的代码

<Spinner
                android:id="@+id/spinner2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="5pt"
                android:layout_marginTop="5pt"
                android:backgroundTint="#d9d9d9"
                android:entries="@array/dropdown_main" />

它应该看起来像这样:

在此输入图片描述

文本字体为Product Sans Bold,颜色为#333333。

2个回答

15

在你开始之前,需要提醒你:如果要添加字体,你需要设置最低 API 版本为 26 或包含 Support Library v26.0(支持 API 版本 16 及以上)。这个例子展示了如何使用 Support Library;唯一的区别是<font-family> 使用 appres-auto 命名空间代替 android

你可以保留 Spinner 不变,但需要在你的 XML 中添加一个 theme 属性值:

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="5pt"
    android:layout_marginTop="5pt"
    android:backgroundTint="#d9d9d9"
    android:entries="@array/dropdown_main"
    android:theme="@style/SpinnerTheme"  />

您的styles.xml可以包含主题:

<style name="SpinnerTheme">
    <item name="android:textColor">#333333</item>
    <item name="android:fontFamily">@font/product_sans</item>
    <item name="android:textStyle">bold</item>
</style>

添加字体需要执行以下几个步骤:

  1. 添加字体文件夹:右键单击res文件夹,选择New > Android resource directory。确保你选择的资源类型是“Font”(通常也包括名称)。
  2. 从类似https://befonts.com/product-sans-font.html的地方将Product Sans字体文件添加到您的项目中。
  3. 右键单击res下的font文件夹,选择New > Font resource file。命名文件为product_sans.xml
  4. 列出您添加的字体:

如果使用支持库,请确保在这里添加app名称空间。否则,如果您处于SDK版本26或更高版本,则可以引用android名称空间。

<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
    <font app:font="@font/product_sans_regular" app:fontWeight="400" app:fontStyle="normal" />
    <font app:font="@font/product_sans_italic" app:fontWeight="400" app:fontStyle="italic" />
    <font app:font="@font/product_sans_bold" app:fontWeight="700" app:fontStyle="normal" />
    <font app:font="@font/product_sans_bold_italic" app:fontWeight="700" app:fontStyle="italic" />
</font-family>

您可以在此处找到有关XML中字体的更多信息:https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml


完美的解决方案! - coderpc
android:fontFamily 是从 API 级别 16 开始支持,而不是 26。 - Aleks N.
@AleksN. - 正确!它需要支持库,我提到了但从未调用那里支持的API级别。 - MFazio23

12
在这里,您可以在布局文件夹中制作自定义的xml文件,您可以添加以下内容:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#333333"
android:padding="10dp"
android:textStyle="bold"  /> 

然后在你的代码中像这样提及它:

val adapter = ArrayAdapter.createFromResource(this, R.array.array_name, R.layout.custom_spinner) // where array_name consists of the items to show in Spinner
adapter.setDropDownViewResource(R.layout.custom_spinner) // where custom-spinner is mycustom xml file. 

然后设置适配器。


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