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

时间:2018-09-01 14:46:46

标签: android kotlin spinner

我想在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" />

它应该看起来像这样:

enter image description here

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

2 个答案:

答案 0 :(得分:2)

在开始之前请先抬头:要添加字体,您将需要将API的最低版本设置为26,或者包括Support Library v26.0。这个例子展示了如何使用支持库。唯一真正的区别是<font-family>使用appres-auto命名空间而不是android

您可以保持微调框不变,但可以在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文件夹,然后选择新建> Android资源目录。确保选择的资源类型为“字体”(可能还有名称)。
  2. https://befonts.com/product-sans-font.html之类的位置将Product Sans字体文件添加到您的项目中。
  3. 右键单击font下的res文件夹,然后选择 New>字体资源文件。将文件命名为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

答案 1 :(得分:1)

在这里您可以在布局文件夹中创建一个自定义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. 

然后设置适配器。

相关问题