And*_*ino 25 fonts android text
可能重复:
是否可以为整个应用程序设置字体?
我需要为整个应用程序设置自定义字体(.ttf格式),我该怎么办?如果可能,从Manifest或XML将是最好的选择
Vic*_*cVu 22
编辑2014年9月:
对于仍然看到这个古老可怕答案的人来说,真正的,好的答案就在这里:
旧:
你最好的选择是:
所以
TextView text = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "yourfont.ttf");
text.setTypeface(font);
Run Code Online (Sandbox Code Playgroud)
将您的.ttf放在"assets"文件夹的根目录中.
Jel*_*lle 11
你可以这样做.创建自定义textview并在任何地方使用它
public class MyTextView extends android.widget.TextView
{
public MyTextView(Context context)
{
this(context, null);
}
public MyTextView(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs);
if (this.isInEditMode()) return ;
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SomeStyle);
final String customFont = a.getString(R.styleable.SomeStyle_font);
//Build a custom typeface-cache here!
this.setTypeface(
Typeface.createFromAsset(context.getAssets(), customFont)
);
}
}
Run Code Online (Sandbox Code Playgroud)
将其添加到attrs.xml
<declare-styleable name="SomeStyle">
<attr name="font" format="string" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
然后在您的主题中,执行以下操作:这将确保所有textview将使用MyTextView样式
<item name="android:textViewStyle">@style/MyTextView</item>
Run Code Online (Sandbox Code Playgroud)
现在,我们可以使用此样式的自定义属性定义自定义字体.
<style name="MyTextView" parent="@android:style/Widget.TextView">
<item name="font">MyPathToFontInAssets.ttf</item>
</style>
Run Code Online (Sandbox Code Playgroud)
因此,无论何时在项目中使用MyTextView,它都将具有您的自定义字体.
重要说明:字体不会被缓存,因此如果您打算使用此代码,则还应构建自定义字体缓存,以便可以为所有文本视图重复使用自定义字体.这将大大加快应用程序的速度!
更新:正如阿米尔所说,这几乎与自定义字体和XML布局(Android)相同,但我也使用Android样式自动在应用程序中的所有文本视图上使用它.
Geo*_*zov 10
Cerate一个TextView子类并在任何地方使用它
public class RobotoTextView extends TextView {
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RobotoTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Light.ttf");
setTypeface(tf);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法
<com.test.RobotoTextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Run Code Online (Sandbox Code Playgroud)
在java代码中,您可以将其强制转换为TextView
小智 7
TextView tv=(TextView)findViewById(R.id.custom);
Typeface face=Typeface.createFromAsset(getAssets(),
"fonts/Verdana.ttf");
tv.setTypeface(face);
Run Code Online (Sandbox Code Playgroud)
将字体文件放在/ res /中的fonts文件夹中
喜欢我的答案,如果它有用...
| 归档时间: |
|
| 查看次数: |
84120 次 |
| 最近记录: |