English 中文(简体)
设置所有文本的字体“ 活动中的意见”?
原标题:Set font for all textViews in activity?

能否在一项活动中设置全部文本视图的字体? 我可以使用下列方法为单一文本设置字体:

    TextView tv=(TextView)findViewById(R.id.textView1); 
    Typeface face=Typeface.createFromAsset(getAssets(), "font.ttf"); 
    tv.setTypeface(face);

但我想立即修改所有文本的意见, 而不是手动为每份文本设置, 任何信息都会受到欢迎!

最佳回答

解答1: 只需将这些方法用父母的过往观点称为论据。

private void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
        }
    } catch (Exception e) {
 }
 }

解答 2: : 您可以使用自定义字体将 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(), "font.ttf");
            setTypeface(tf);
        }
    }

}
问题回答

我个人收藏的那本

private void setFontForContainer(ViewGroup contentLayout) {
    for (int i=0; i < contentLayout.getChildCount(); i++) {
        View view = contentLayout.getChildAt(i);
        if (view instanceof TextView)
            ((TextView)view).setTypeface(yourFont);
        else if (view instanceof ViewGroup)
            setFontForContainer((ViewGroup) view);
    }
}

如果您正在寻找更一般的程序解答, 我创建了一个静态类, 可用于设置整个视图的外观( 活动界面) 。 请注意, 我正与 Mono (C#) 合作, 但是您可以使用 Java 轻松地执行它 。

您可以通过此类的布局或特定视图, 您想要自定义它。 如果您想要超级高效, 您可以使用 Singleton 模式执行它 。

public static class AndroidTypefaceUtility 
{
    static AndroidTypefaceUtility()
    {
    }
    //Refer to the code block beneath this one, to see how to create a typeface.
    public static void SetTypefaceOfView(View view, Typeface customTypeface)
    {
    if (customTypeface != null && view != null)
    {
            try
            {
                if (view is TextView)
                    (view as TextView).Typeface = customTypeface;
                else if (view is Button)
                    (view as Button).Typeface = customTypeface;
                else if (view is EditText)
                    (view as EditText).Typeface = customTypeface;
                else if (view is ViewGroup)
                    SetTypefaceOfViewGroup((view as ViewGroup), customTypeface);
                else
                    Console.Error.WriteLine("AndroidTypefaceUtility: {0} is type of {1} and does not have a typeface property", view.Id, typeof(View));
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("AndroidTypefaceUtility threw:
{0}
{1}", ex.GetType(), ex.StackTrace);
                    throw ex;
                }
            }
            else
            {
                Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / view parameter should not be null");
            }
        }

        public static void SetTypefaceOfViewGroup(ViewGroup layout, Typeface customTypeface)
        {
            if (customTypeface != null && layout != null)
            {
                for (int i = 0; i < layout.ChildCount; i++)
                {
                    SetTypefaceOfView(layout.GetChildAt(i), customTypeface);
                }
            }
            else
            {
                Console.Error.WriteLine("AndroidTypefaceUtility: customTypeface / layout parameter should not be null");
            }
        }

    }

在您的活动中, 您需要创建一个 Typeface 对象。 在 OnCreate () 中, 我使用在我的资源/ Assets/ 目录中放置的. ttf 文件创建地雷 。 请确保该文件在其属性中标记为 Android Assolution 资产 。

protected override void OnCreate(Bundle bundle)
{               
    ...
    LinearLayout rootLayout = (LinearLayout)FindViewById<LinearLayout>(Resource.Id.signInView_LinearLayout);
    Typeface allerTypeface = Typeface.CreateFromAsset(base.Assets,"Aller_Rg.ttf");
    AndroidTypefaceUtility.SetTypefaceOfViewGroup(rootLayout, allerTypeface);
}

<强 > 最佳答案

< 强度 > 1. 设置一个文本的自定义字体View

Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "Fonts/FontName.ttf");
textView.setTypeface (typeface);

<强>2. 为所有文本设置自定义字体

创建像下面一样的 JavaClass

public class CustomFont extends android.support.v7.widget.AppCompatTextView {

    public CustomFont(Context context) {
        super(context);
        init();
    }

    public CustomFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomFont(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/FontName.ttf");
            setTypeface(tf);
    }
}

在您的 xml 页面中

<packageName.javaClassName>

...

/>

gt;

    <com.mahdi.hossaini.app1.CustomFont
    android:id="@+id/TextView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="KEEP IT SIMPLE"
    android:textAlignment="center" />

正在扩展 Agarwal 的回答... 您可以改变您的文本视图的样式, 设置常规、 大胆、 斜体等 。

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class TextViewAsap extends TextView {

    public TextViewAsap(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public TextViewAsap(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TextViewAsap(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.DEFAULT;

            switch (getTypeface().getStyle()) {
                case Typeface.BOLD:
                    tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Bold.ttf");
                    break;

                case Typeface.ITALIC:
                    tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf");
                    break;

                case Typeface.BOLD_ITALIC:
                    tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Italic.ttf");
                    break;

                default:
                    tf = Typeface.createFromAsset(getContext().getAssets(), "Fonts/Asap-Regular.ttf");
                    break;
            }

            setTypeface(tf);
        }
    }

}

You can create your Assets folder like this: Create Assets

您的“ 资产” 文件夹应该这样看 :

最后,您在 xml 中的 TextView 应该是 TextViewAsap 类型视图。 现在它可以使用您编码的任何样式...

<com.example.project.TextViewAsap
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Example Text"
                android:textStyle="bold"/>

example of more "generic" way with use of reflection:

** 它提出了一个让观众群体儿童方法参与的想法, 方法设置为 TextSize( int, float), 但您可以像问题一样使用它来设置 TypeFace () 。

 /**
 * change text size of view group children for given class
 * @param v - view group ( for example Layout/widget)
 * @param clazz  - class to override ( for example EditText, TextView )
 * @param newSize - new font size
 */
public static void overrideTextSize(final View v, Class<?> clazz, float newSize) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideTextSize(child, clazz, newSize);
            }
        } else if (clazz.isAssignableFrom(v.getClass())) {
            /** create array for params */
            Class<?>[] paramTypes = new Class[2];
            /** set param array */
            paramTypes[0] = int.class;  // unit
            paramTypes[1] = float.class; // size
            /** get method for given name and parameters list */
            Method method = v.getClass().getMethod("setTextSize",paramTypes);
            /** create array for arguments */
            Object arglist[] = new Object[2];
            /** set arguments array */
            arglist[0] = TypedValue.COMPLEX_UNIT_SP;
            arglist[1] = newSize;
            /** invoke method with arguments */
            method.invoke(v,arglist);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

<强 > > 音响:

使用反射应该非常小心。 反射类非常“ 强” 例外 < / 强” 。

  • for example, you should check for the presence of annotations to prevent different kinds of problems. In the case of method SetTextSize () It is desirable to check the annotations android.view.RemotableViewMethod

您可以使用风格继承。

您的活动中的文本视图是否都通过 android:textAppearence 而不是手动 android:typeface 来声明样式 。

然后,让每个风格都继承活动风格,就像这样:

<TextView ...
      android:textAppearance="@style/item_name"/>
<TextView ...
      android:textAppearance="@style/item_details"/>

在. xml 样式中:

<style name="ActivityStyle">
    <item name="android:fontFamily">@font/font</item>
</style>
<style name="item_name" parent="ActivityStyle">
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">20sp</item>
</style>
<style name="item_details" parent="ActivityStyle">
    <item name="android:textSize">15sp</item>
</style>




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签