3 android android-emulator android-intent android-layout android-listview
我有一个关于向textview添加多个自定义字体的问题.我基本上已经在fonts文件夹中添加了字体,并基于我在网上找到的解决方案为fonttextview创建了一个java类.但是我看到他们只添加了一种字体,我想添加多种字体,如roboto-regular,roboto-bold,cab-bold等.这是我到目前为止的代码:
public class FontTextView extends TextView {
public FontTextView(Context context) {
super(context);
Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf");
this.setTypeface(face);
}
public FontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf");
this.setTypeface(face);
}
public FontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Typeface face=Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf");
this.setTypeface(face);
}
Run Code Online (Sandbox Code Playgroud)
如何创建多种字体呢?此外,我尝试了样式等,但它显示错误,因为它不支持可定制的类,任何人都可以添加另一种字体到这个现有的代码并引导我完成检索过程?
谢谢!贾斯汀
对于设置为xml文件的不同字体,请使用以下代码.
public class CustomTextView extends TextView {
private static final String TAG = "CustomTextView";
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs,R.styleable.CustomTextView);
String customFont = a.getString(R.styleable.CustomTextView_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), "fonts/"+asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
Run Code Online (Sandbox Code Playgroud)
}
在xml文件中,您可以将其用作:
<com.package_name.CustomTextView
your_name:customFont="arialbd.ttf" />
Run Code Online (Sandbox Code Playgroud)
和int主要的父布局添加
xmlns:your_name="http://schemas.android.com/apk/res/com.package_name"
Run Code Online (Sandbox Code Playgroud)
并记得在values文件夹中添加一个attrs.xml,其中包含以下resource内容
<resources>
<declare-styleable name="CustomTextView">
<attr name="customFont" format="string"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
4215 次 |
| 最近记录: |