我想在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
在这里,您可以在布局文件夹中创建一个自定义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.
然后设置适配器。
在开始之前进行提示:要添加字体,您要么将最低API版本设置为26,要么包含支持库v26.0。此示例显示如何使用支持库;唯一真正的区别是<font-family>
使用app
或res-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>
要添加字体,您需要做一些事情:
res
文件夹,然后选择“新建”>“Android资源目录”。确保选择“字体”的资源类型(也可能是名称)。font
下的res
文件夹,然后选择New> Font resource file。将文件命名为product_sans.xml
。如果您正在使用支持库,请确保在此处添加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