如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
如何改变文本/字体设置在一个Android TextView?
例如,如何使文本加粗?
当前回答
你可以这样做
ty.setTypeface(Typeface.createFromAsset(ctx.getAssets(), "fonts/magistral.ttf"), Typeface.BOLD);
其他回答
通过XML:
android:textStyle="bold"
通过Java:
//Let's say you have a textview
textview.setTypeface(null, Typeface.BOLD);
在使用自定义字体,但没有粗体字体的情况下,可以使用:
myTextView.setText(Html.fromHtml("<b>" + myText + "</b>");
如果你在画它,那么这个就可以做到:
TextPaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);
你可以用这个字体
创建一个类名TypefaceTextView并扩展TextView
私有静态Map 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>();
}
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();
}
}
将字体粘贴到资源文件夹中创建的字体文件夹中
<packagename.TypefaceTextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:text="TRENDING TURFS"
android:textColor="#000"
android:textSize="20sp"
app:customTypeface="fonts/pompiere.ttf" />**here pompiere.ttf is the font name**
将这些行放在xml的父布局中
xmlns:app="http://schemas.android.com/apk/res/com.mediasters.wheresmyturf"
xmlns:custom="http://schemas.android.com/apk/res-auto"
在理想的情况下,你应该在你的布局XML定义中设置文本样式属性,就像这样:
<TextView
android:id="@+id/TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"/>
通过使用setTypeface方法,有一个简单的方法可以在代码中动态地实现相同的结果。你需要传递一个Typeface类的对象,它将描述TextView的字体样式。因此,要实现与上面XML定义相同的结果,您可以执行以下操作:
TextView Tv = (TextView) findViewById(R.id.TextView);
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);
Tv.setTypeface(boldTypeface);
第一行将创建对象表单预定义的样式(在本例中为字体。BOLD,但还有更多预定义的)。一旦我们有了一个字体实例,我们就可以在TextView上设置它。这就是我们的内容将显示在我们定义的样式上。
我希望这对你有很大帮助。欲了解更多信息,请访问
http://developer.android.com/reference/android/graphics/Typeface.html