我想为
TextView
中的文本设置样式或字体,就像下面显示的图片一样:TextView
中的文本设置样式或字体,就像下面显示的图片一样:<TextView
style="@style/CodeFont"
android:text="@string/hello" />
你需要将那段代码的字体样式设置为:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
你需要一个自定义字体,然后你可以这样做:
Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
MyTextView.setTypeface(mFont);
TextView
。如果您更喜欢这种方法,请参考我之前给出的此答案。如果您想在多个TextView上进行更改,还有另一种方法:使用类:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Ubuntu-L.ttf");
setTypeface(tf);
}
}
}
并且在布局中替换:
<TextView
...
/>
使用:
<com.WHERE_YOUR_CLASS_IS.MyTextView
...
/>
textView.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
style="@android:style/Holo.ButtonBar" >
如果你不喜欢这个,那么你可以创建自己的样式。就像这样:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Custom" parent="@android:style/TextAppearance.Large" >
<item name="android:typeface">monospace</item>
</style>
</resources>
并在布局文件中将样式更改为类似以下内容:
style="@style/Custom"