在android中为整个布局设置字体

时间:2012-02-17 00:28:19

标签: android layout fonts

我一直在Android中使用自定义字体。我知道如何导入字体并将文本视图设置为该字体。我注意到,一旦你有很多textViews,这可能会变得相当繁琐。

是否有将整个布局字体类型设置为某个字体?

提前致谢。

2 个答案:

答案 0 :(得分:1)

我所做的是声明我自己的TextView子类,我在构造函数中设置字体,如下所示:

public class MyTextView extends TextView {

public MyTextView(Context context) {
    super(context);
    setTypeFace();
}


public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setTypeFace();
}


public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setTypeFace();
}

public void setTypeFace()
{
    this.setTypeface(StaticUtils.getDefaultFontNormal(getContext()));
}

}

然后在我的布局中,如果我使用完全限定名称,它可以工作:

<ca.mycompany.mobile.ui.support.MyTextView
        android:id="@+id/title_summaryreports"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="10dip"
            android:paddingTop="10dip"
            android:text="@string/title_strategies"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textStyle="bold"
            android:textColor="#ff0000" />

答案 1 :(得分:0)

您可以使用此方法,只需将顶级视图组ID和字体字体传递给此方法,这会将字体设置为整个布局。

public void setFont(ViewGroup group, Typeface lTypeface)
{
    int count = group.getChildCount();
    View v;
    for (int i = 0; i < count; i++)
    {
        v = group.getChildAt(i);
        if (v instanceof TextView)
        {
            ((TextView) v).setTypeface(lTypeface);
        } else if (v instanceof EditText)
        {
            ((EditText) v).setTypeface(lTypeface);
        } else if (v instanceof Button)
        {
            ((Button) v).setTypeface(lTypeface);
        } else if (v instanceof TextInputLayout)
        {
            ((TextInputLayout) v).setTypeface(lTypeface);
        } else if (v instanceof ViewGroup)
            setFont((ViewGroup) v, lTypeface);
    }
}