【发布时间】:2014-04-20 03:33:39
【问题描述】:
在 Android 中使用字体的正确方法是什么?我看到许多使用自定义 XML 标记进行文本视图的示例。我尝试在 Java 中设置为普通文本视图,它工作正常,那么使用自定义字段的原因是什么?
【问题讨论】:
标签: android fonts android-typeface
在 Android 中使用字体的正确方法是什么?我看到许多使用自定义 XML 标记进行文本视图的示例。我尝试在 Java 中设置为普通文本视图,它工作正常,那么使用自定义字段的原因是什么?
【问题讨论】:
标签: android fonts android-typeface
使用自定义字体时,最好将字体添加到项目中的 /assets 目录。执行以下操作是相当轻量级的:
TextView customTypefaceTextView = (TextView) findViewById(R.id.customTypefaceTextView);
Typeface customTypeface = Typeface.createFromAsset(getAssets(), "Custom_Typeface.ttf");
customTypefaceTextView.setTypeface(customTypeface);
请记住,查找资产将与当前的 Context 相关,因此如果您在 Fragment 与 Activity 中使用自定义字体,您将需要调用 getActivity().getAssets() 而不仅仅是 getAssets()。
这是对来自http://code.tutsplus.com/tutorials/customize-android-fonts--mobile-1601的快速提示的参考
此外,创建一个extends TextView 的类可能更实用,以帮助您对自定义字体进行更实用的实现,该自定义字体可用于您想要添加自定义字体的TextViews,如下所示:
public class CustomTitleTextView extends TextView {
private Context m_classContext = null;
private Typeface m_customTypeFace = null;
// Default Constructor
public CustomTitleTextView(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.m_classContext = context;
createRobotoTitleTextView();
}
// Default Constructor
public CustomTitleTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
this.m_classContext = context;
createRobotoTitleTextView();
}
// Default Constructor
public CustomTitleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.m_classContext = context;
createRobotoTitleTextView();
}
// Adds the Typeface to the TextView
private void createRobotoTitleTextView()
{
m_customTypeFace = Typeface.createFromAsset(m_classContext.getAssets(), "Roboto-Thin.ttf");
this.setTypeface(m_customTypeFace);
}
}
然后您可以在 XML 中的任何布局中使用它
<packagename.CustomTitleTextView
android:id="@+id/customTitleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
更新
这些是我成功实现自定义字体的几种方法。该示例展示了如何通过extends TextView 添加自定义TextView 然后将其添加到XML 中不是必需的,它只是提供了如何将TextView 创建为可重用对象而不是在您的活动中动态创建的框架或片段。
祝你好运!
【讨论】:
<packagename.CustomTitleTextView`android:id="@+id/customTitleTextView"``android:layout_width="wrap_content"``android:layout_height= “wrap_content”/>`那我为什么需要这些?我有正常的文本视图,例如`