我想为我正在创建的 Android 应用程序使用自定义字体。
我可以从代码中单独更改每个对象的字体,但我有数百个对象。
So,
- 有没有办法从 XML 中做到这一点? [设置自定义字体]
- 有没有一种方法可以从一个地方的代码中做到这一点,即整个应用程序和所有组件都应该使用自定义字体而不是默认字体?
对的,这是可能的。
您必须创建一个扩展文本视图的自定义视图。
In attrs.xml
in values
folder:
<resources>
<declare-styleable name="MyTextView">
<attr name="first_name" format="string"/>
<attr name="last_name" format="string"/>
<attr name="ttf_name" format="string"/>
</declare-styleable>
</resources>
In main.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:lht="http://schemas.android.com/apk/res/com.lht"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello"/>
<com.lht.ui.MyTextView
android:id="@+id/MyTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello friends"
lht:ttf_name="ITCBLKAD.TTF"
/>
</LinearLayout>
In MyTextView.java
:
package com.lht.ui;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class MyTextView extends TextView {
Context context;
String ttfName;
String TAG = getClass().getName();
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
for (int i = 0; i < attrs.getAttributeCount(); i++) {
Log.i(TAG, attrs.getAttributeName(i));
/*
* Read value of custom attributes
*/
this.ttfName = attrs.getAttributeValue(
"http://schemas.android.com/apk/res/com.lht", "ttf_name");
Log.i(TAG, "firstText " + firstText);
// Log.i(TAG, "lastText "+ lastText);
init();
}
}
private void init() {
Typeface font = Typeface.createFromAsset(context.getAssets(), ttfName);
setTypeface(font);
}
@Override
public void setTypeface(Typeface tf) {
// TODO Auto-generated method stub
super.setTypeface(tf);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)