将字体设置为 android 中的列表视图项目

Set typeface to listview items in android

我需要为列表视图项添加自定义字体。我已经使用像这样的适配器将值添加到列表中

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), newList, R.layout.club_list2, from, to);

这里我想为 club_list2 布局中的文本视图设置字体。这怎么可能?

如果您希望它们都使用同一个,请在 xml 中使用 android:typeface。如果您希望他们使用不同的,请在您的 getView 函数中将其设置在 TextView 上。

默认不是Arial。默认为 Droid Sans。

更改为不同的内置字体

其次,要更改为不同的内置字体,请在布局 XML 中使用 android:typeface 或在 Java(android).

例子

Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/Arial.otf");
TextView tv = (TextView) findViewById(R.id.CustomFontText);
tv.setTypeface(tf)

如果您想从 xml 设置自定义字体,您可以这样做

public class TypefaceTextView extends TextView {

    private static Map<String, Typeface> mTypefaces;

    public TypefaceTextView(final Context context) {
        this(context, null);
    }

    public TypefaceTextView(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TypefaceTextView(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        if (mTypefaces == null) {
            mTypefaces = new HashMap<String, Typeface>();
        }

        // prevent exception in Android Studio / ADT interface builder
        if (this.isInEditMode()) {
            return;
        }

        final TypedArray array = context.obtainStyledAttributes(attrs, styleable.TypefaceTextView);
        if (array != null) {
            final String typefaceAssetPath = array.getString(
                    R.styleable.TypefaceTextView_customTypeface);

            if (typefaceAssetPath != null) {
                Typeface typeface = null;

                if (mTypefaces.containsKey(typefaceAssetPath)) {
                    typeface = mTypefaces.get(typefaceAssetPath);
                } else {
                    AssetManager assets = context.getAssets();
                    typeface = Typeface.createFromAsset(assets, typefaceAssetPath);
                    mTypefaces.put(typefaceAssetPath, typeface);
                }

                setTypeface(typeface);
            }
            array.recycle();
        }
    }

}

在 xml.

<com.example.TypefaceTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="30sp"
        android:text="@string/hello_world"
        geekui:customTypeface="fonts/yourfont.ttf" />

你的字体应该在 asset/fonts/ 文件夹

在 values 中创建资源文件并将其设置为名称 attrs.xml

然后复制过去

<resources>

    <declare-styleable name="TypefaceTextView">
        <attr name="customTypeface" format="string" />
    </declare-styleable>

</resources>