带有自定义文本字体和颜色的微调器

Arf*_*ann 9 android spinner kotlin

我想在 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" />
Run Code Online (Sandbox Code Playgroud)

它应该是这样的:

在此处输入图片说明

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

MFa*_*o23 12

开始之前请注意:要添加字体,您需要将最低 API 版本设置为 26,或者包含支持库 v26.0(从 API 版本 16 开始支持)。这个例子展示了如何使用支持库;唯一真正的区别是<font-family>使用apporres-auto命名空间而不是android.

您可以保持微调器不变,但theme向您的 XML添加一个值:

<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"  />
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

要添加字体,您需要做一些事情:

  1. 添加字体文件夹:右键单击您的res文件夹并选择New > Android resource directory。确保选择“字体”的资源类型(可能还有名称。)
  2. https://befonts.com/product-sans-font.html 之类的地方将 Product Sans 字体文件添加到您的项目中。
  3. 右键单击下面的font文件夹res并选择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>
Run Code Online (Sandbox Code Playgroud)

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


Avi*_*ash 9

在这里,您可以在布局文件夹中创建一个自定义 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"  /> 
Run Code Online (Sandbox Code Playgroud)

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

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. 
Run Code Online (Sandbox Code Playgroud)

然后设置适配器。