我需要更改TextView文本的字体。我尝试使用此方法,但它会更改整个应用程序的字体。
Typeface tfArial = Typeface.createFromAsset(mFragment.getContext().getAssets(), "fonts/arial.ttf");
mEmailInput.setTypeface(tfArial);
是否有方法或方法只更改单词的字体而不更改整个应用程序字体?
谢谢!
答案 0 :(得分:0)
创建自定义文字视图:
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(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.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
添加xml文件:
<com.mypackage.TextViewPlus
android:id="@+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="@string/showingOffTheNewTypeface"
foo:customFont="my_font_name_regular.otf">
</com.mypackage.TextViewPlus>
答案 1 :(得分:0)
在布局文件(.xml)中,您需要转到要更改字体的TextEdit,并在Java中使用android:typeface
或setTypeface()
。
请记住,Arial不适用于Android,因此您需要将Arial.ttf放在assets文件夹中 (内部资源文件夹创建名为fonts的新文件夹并将其放在其中。) 然后在你的java代码中右键:
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf");
textView.setTypeface(type);
答案 2 :(得分:0)
您可以通过三种方式将字体设置为特定字词:
1&GT;
String first = "This is test";
String next = "<font color='#EE0000'>Application</font>";
t.setText(Html.fromHtml(first + next));
2 - ;
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString str1= new SpannableString("Text1");
str1.setSpan(new ForegroundColorSpan(Color.RED), 0, str1.length(), 0);
builder.append(str1);
SpannableString str2= new SpannableString(appMode.toString());
str2.setSpan(new ForegroundColorSpan(Color.GREEN), 0, str2.length(), 0);
builder.append(str2);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setText( builder, TextView.BufferType.SPANNABLE);
3&GT;
String first = "This word is ";
String next = "red"
TextView tvText= (TextView) findViewById(R.id.textbox);
tvText.setText(first + next, BufferType.SPANNABLE);
Spannable s = (Spannable)t.getText();
int start = first.length();
int end = start + next.length();
s.setSpan(new ForegroundColorSpan(0xFFFF0000), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
在第3个解决方案中,您还可以设置起始位置和结束位置来设置字体或可跨越字符串。
希望这对你有所帮助。