我使用android studio来创建一个Android应用程序。我的API版本高于16,我使用支持库26.我在res-> font下创建了一个字体系列,我命名为“cairo_regular.ttf”。在我的Android应用程序中,在我的一个界面中,我使用带有下拉样式的Spinner来显示所有国家/地区的列表,以下是xml代码:
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="16dp"
android:prompt="@string/spinner_title" />
我在类java中的构造函数外声明了适配器,即:
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, countryTab);
country.setAdapter(arrayAdapter);
我在layout文件夹中制作了自定义xml文件,如下所示:
<android.support.v7.widget.AppCompatTextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/text1"
style="?android:attr/dropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:singleLine="true"
android:fontFamily="@font/cairo_regular"
android:textAppearance="?android:attr/textAppearanceLargePopupMenu" />
我在自定义xml文件中添加“android:fontFamily =”@ font / cairo_regular“”以更改微调器中国家/地区列表的字体,但字体不会更改。我想知道如何在我的应用程序中更改Spinner的fontfamilly。
我是这样做的:
FontCache类:
import android.content.Context;
import android.graphics.Typeface;
import java.util.HashMap;
public class FontCache {
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
然后创建一个扩展TextView的自定义类:
public class MontserratRegularTextView extends android.support.v7.widget.AppCompatTextView {
public MontserratRegularTextView(Context context) {
super(context);
applyCustomFont(context);
}
public MontserratRegularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context);
}
public MontserratRegularTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context);
}
private void applyCustomFont(Context context) {
Typeface customFont = FontCache.getTypeface("fonts/Montserrat-Regular.otf", context);//your font path here
setTypeface(customFont);
}
}
然后将其添加到您正在制作的自定义xml文件中:
<com.example.myapplication.customFonts.MontserratRegularTextView
android:id="@+id/user_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/nav_header_title"
/>
希望这对你有所帮助!