【问题标题】:Efficient Way to customize Font [duplicate]自定义字体的有效方法[重复]
【发布时间】:2012-09-17 14:48:54
【问题描述】:

可能重复:
Android - Using Custom Font

在 Android 应用程序中自定义字体的最佳或有效方法是什么?我一直在尝试自定义我的 Textviews 和 Edittexts,但我的应用程序有点慢,因为我正在使用自定义字体并且占用大量内存,有时甚至崩溃。

【问题讨论】:

    标签: android memory fonts textview


    【解决方案1】:

    我严重怀疑您的应用程序运行缓慢是因为您使用了自定义字体。这可能是您应用它们的方式。通常,我会在我的 Activity 中执行以下操作:

    //Get an instance to the root of your layout (outermost XML tag in your layout
    //document)
    ViewGroup root = (ViewGroup)findViewById(R.id.my_root_viewgroup);
    
    //Get one reference to your Typeface (placed in your assets folder)
    Typeface font = Typeface.createFromAsset(getAssets(), "My-Font.ttf");
    
    //Call setTypeface with this root and font
    setTypeface(root, font);
    
    public void setTypeface(ViewGroup root, Typeface font) {
        View v;
    
        //Cycle through all children
        for(int i = 0; i < root.getChildCount(); i++) {
            v = root.getChildAt(i);
    
            //If it's a TextView (or subclass, such as Button) set the font
            if(v instanceof TextView) {
                ((TextView)v).setTypeface(font);
    
            //If it's another ViewGroup, make a recursive call
            } else if(v instanceof ViewGroup) {
                setTypeface(v, font);
            }
        }
    }
    

    这样您只保留一个对您的字体的引用,并且您不必对任何视图 ID 进行硬编码。

    您也可以将其构建到Activity 的自定义子类中,然后让您的所有 Activity 扩展您的自定义 Activity 而不是仅仅扩展 Activity,然后您只需编写一次此代码。

    【讨论】:

    • 这样不会消耗很多内存吧?
    • 不。出于好奇,你认为为什么会这样?
    • 您每次获得TextView时都在设置字体,所以对于每个textView它不会单独分配内存?除此之外,我正在使用一个包含大量项目的 ListView。
    • 是的,我在我的 ListViews 中使用数百个项目执行此操作没有问题。只要它是一个类变量并且您没有为每个项目创建新的字体引用,它将为每个 TextView 使用相同的字体引用。
    • 只需在你膨胀的那个布局上调用 setTypeface,而不是你用findViewById() 找到的那个。您可以将 any ViewGroup 传递给该方法,无论您是通过 ID 找到它还是在代码中添加它,它都会起作用。
    猜你喜欢
    • 2017-02-05
    • 2011-11-06
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多