在 android 中,如何一次为整个 Activity
或 Fragment
设置字体颜色和字体样式,这样我就不必为每个设置了和每个 TextView
?
最佳答案
这是我的自定义 TextView 类,
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomTextView(Context context) {
super(context);
init();
}
public void init() {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
"fonts/Montserrat-Regular.ttf");
setTextAppearance(getContext(), android.R.style.headerText); //Here is the code for adding textview style.
setTypeface(tf, 1);
}
}
在 xml 中,我使用了我的自定义 textview 而不是默认的 Textview,
<com.sample.android.utils.CustomTextView
android:id="@+id/login_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:clickable="true"
android:text="Log In"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/login_page_text_normal"
android:textStyle="bold" />
或者你只需要设置textstyle的意思,在你的styles.xml中加入这段代码,
<style name="headerText">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#ffffff</item>
<item name="android:gravity">center</item>
<item name="android:textSize">8.39pt</item>
<item name="android:textStyle">bold</item>
<item name="android:shadowColor">#000000</item>
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
<item name="android:adjustViewBounds">true</item>
<item name="android:singleLine">true</item>
</style>
然后在你的 xml 布局中添加这个
<TextView
android:id="@+id/header_text"
style="@style/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
关于android - 为整个 Activity 设置字体设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20346123/