【问题标题】:How to set custom (arial )type face via xml not via a java code如何通过xml而不是通过java代码设置自定义(arial)字体
【发布时间】:2011-07-29 07:16:44
【问题描述】:

我已经意识到这一点:- 字体 typefaceArial= Typeface.createFromAsset(context.getAssets(), "arial.ttf");

但是当我创建以下类时它可以工作,但它给出了内存不足警告问题。

公共类 MidColorTextView 扩展 TextView {

private CharSequence text;
private String token;
private static Context context;
private String colorSpan;
private int colorCode;
private static Typeface typefaceArial;

public MidColorTextView( Context context , AttributeSet attrs )
{
    super(context, attrs);
    this.context=null;
    this.context = context;


    for(int i = 0; i < attrs.getAttributeCount(); i ++ )
    {
        // Log.i(TAG, attrs.getAttributeName(i));
        /*
         * Read value of custom attributes
         */

        this.text = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.lht", "text");

        this.token = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.lht", "token");
        this.colorSpan = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.lht", "colorSpan");
        // Log.i("TAG", "token " + token);
        // Log.i("TAG", "text " + text);
        // Log.i("TAG", "colorSpan " + colorSpan);

    }
    init();
}

private void init ()
{
    if(text.charAt(0) == '@')
    {
        String tempText = (String) text.subSequence(1, text.length());
        this.text = Html.fromHtml(getResources().getString(Integer.parseInt(tempText)));

    }
    if(token.charAt(0) == '@')
    {
        String tempText = (String) token.subSequence(1, token.length());
        this.token = getResources().getString(Integer.parseInt(tempText));
    }
    if(colorSpan.charAt(0) == '@')
    {
        String tempText = (String) colorSpan.subSequence(1, colorSpan.length());
        this.colorSpan = getResources().getString(Integer.parseInt(tempText));
    }

    setColorCode(Color.parseColor(colorSpan));

    CharSequence textWitoutToken = null;
    String tempString = text.toString();

    // ---------checking whether text containg token or not.
    if(tempString.contains(token))
    {
        textWitoutToken = setSpanBetweenTokens(text, token, new ForegroundColorSpan(colorCode));
    }
    else
    {
        textWitoutToken = text;
    }
    textContent = null;
    setText(textWitoutToken);
    setTypefaceArial ();
    setTypeface(getTypefaceArial ());

}



public int getColorCode ()
{
    return colorCode;
}

public void setColorCode ( int colorCode )
{
    this.colorCode = colorCode;
}

private CharSequence textContent;


public static Typeface getTypefaceArial ()
{
    return typefaceArial;
}
public static void setTypefaceArial ()
{
    MidColorTextView.typefaceArial= Typeface.createFromAsset(context.getAssets(), "arial.ttf");
}

}

【问题讨论】:

    标签: android textview


    【解决方案1】:

    您可以将字体应用为style

    但特定字体,仅在java代码中:ApiDemo

    要了解导致内存不足错误的原因,

    • 确保该特定字体没有问题(例如,尝试this font,它已在this example of a class extending TextView 中使用。

    • 减少非特定代码并使用最少的代码(即typefaceArial=Typeface.createFromAsset(context.getAssets(), "arial.ttf")this.text ="Testing text"; 作为构造函数的一部分,消除所有attrs.getAttributeValue() 方法,特别是init()方法等)

    一旦您进行了这两项更改,您将能够判断字体分配是否存在问题或其他问题。

    【讨论】:

    • 感谢您的回复。但我已经通过 xml 完成了,但我遇到了前面提到的内存不足警告的问题
    • 是的,我运行了测试用例并删除了 attrs 和 init()。但这只是因为字体。 groups.google.com/group/android-ndk/browse_thread/thread/… 这篇文章中的相同问题但无法解决问题。感谢您宝贵的时间。
    • 发布您的简化代码,以便人们查看。另外,为什么构造函数中有this.context=null;this.context = context;
    • 我只是在尝试一些东西,我在下面的帖子中简化了代码,谢谢你的考虑。
    【解决方案2】:

    我通过使用单例类解决了这个问题。 我提供了完整的代码,以便它可以帮助其他人。

    1. 在 XML 中定义:

        xmlns:lht="http://schemas.android.com/apk/res/com.lht"     android:id="@+id/basicLayout"
    
        <com.xyz.util.MidColorTextView
                xyz:token="#" 
                xyz:colorSpan="@color/BrightRed"
                xyz:text="@string/AppraisingStaffBottomText_imanage"
                style="@style/contentDescriptionText" />
    

    2.创建类MidColorTextView

        package com.xyz.util;
    
        public class MidColorTextView extends TextView {
    
        private CharSequence text;
        private String token;
        private  Context context;
        private String colorSpan;
        private int colorCode;
    
    
        public MidColorTextView( Context context , AttributeSet attrs ) {
            super(context, attrs);
            this.context = context;
    
    
            for(int i = 0; i < attrs.getAttributeCount(); i ++ ) {
                // Log.i(TAG, attrs.getAttributeName(i));
                /*
                 * Read value of custom attributes
                 */
    
                this.text = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.xyz", "text");
    
                this.token = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.xyz", "token");
                this.colorSpan = attrs.getAttributeValue("http://schemas.android.com/apk/res/com.xyz", "colorSpan");
                // Log.i("TAG", "token " + token);
                // Log.i("TAG", "text " + text);
                // Log.i("TAG", "colorSpan " + colorSpan);
    
            }
            init();
        }
    
        private void init () {
    
            if(text.charAt(0) == '@') {
                String tempText = (String) text.subSequence(1, text.length());
                this.text = Html.fromHtml(getResources().getString(Integer.parseInt(tempText)));
    
            }
            if(token.charAt(0) == '@') {
                String tempText = (String) token.subSequence(1, token.length());
                this.token = getResources().getString(Integer.parseInt(tempText));
            }
            if(colorSpan.charAt(0) == '@')
            {
                String tempText = (String) colorSpan.subSequence(1, colorSpan.length());
                this.colorSpan = getResources().getString(Integer.parseInt(tempText));
            }
    
            setColorCode(Color.parseColor(colorSpan));
    
            CharSequence textWitoutToken = null;
            String tempString = text.toString();
    
            // ---------checking whether text containg token or not.
            if(tempString.contains(token))
            {
                textWitoutToken = setSpanBetweenTokens(text, token, new ForegroundColorSpan(colorCode));
            }
            else
            {
                textWitoutToken = text;
            }
            textContent = null;
            setText(textWitoutToken);
            setTypeface(FontManager.getInstance(context).getTypefaceArial ());
    
        }
    
        public void setText ( CharSequence text , String token , int color )
        {
            setText(setSpanBetweenTokens(text, token, new ForegroundColorSpan(color)));
    
            setTypeface(FontManager.getInstance(context).getTypefaceArial ());
    
        }
    
        public int getColorCode ()
        {
            return colorCode;
        }
    
        public void setColorCode ( int colorCode )
        {
            this.colorCode = colorCode;
        }
    
        private CharSequence textContent;
    
        public CharSequence setSpanBetweenTokens ( CharSequence text , String token , CharacterStyle... cs )
        {
            // Start and end refer to the points where the span will apply
            int tokenLen = token.length();
            int start = text.toString().indexOf(token) + tokenLen;
            int end = text.toString().indexOf(token, start);
            if(start > - 1 && end > - 1)
            {
                // Copy the spannable string to a mutable spannable string
                SpannableStringBuilder ssb = new SpannableStringBuilder(text);
                for(CharacterStyle c : cs)
                {
                    ssb.setSpan(c, start, end, 0);
                }
                // Delete the tokens before and after the span
                ssb.delete(end, end + tokenLen);
                ssb.delete(start - tokenLen, start);
    
                text = ssb;
                textContent = ssb;
                String tempString = textContent.toString();
                if(tempString.contains(token))
                {
                    setSpanBetweenTokens(textContent, token, new ForegroundColorSpan(colorCode));
                }
    
            }
    
            return textContent;
        }
    
        }
    

    3.创建类FontManager

    public class FontManager {
        private Typeface typefaceArial;
        private  Context context;
    
        private static FontManager instance = null;
    
        private FontManager(Context context) {
            this.context = context;
            this.typefaceArial= Typeface.createFromAsset(context.getAssets(), "arial.ttf");
        }
    
        public synchronized static FontManager getInstance(Context context) {
            if(instance == null) {
                instance = new FontManager(context);
            }
            return instance;
        }
    
        public Typeface getTypefaceArial () {
            return typefaceArial;
        }
    
    }
    

    这将解决你所有的问题。

    setSpanBetweenTokens 用于特定标记之间的彩色文本。

    这里是一个字符串资源来测试:

    <string name="AppraisingStaffBottomText_imanage">The meeting&lt;br>&lt;br>PAST&lt;br>Allow the employee to give you
            their view of their positive
            progress over the past period, focus them on this with open
            questions, such as:&lt;br>&lt;i>#\"What has been your important contribution over the past
            6
            months?\"#&lt;/i>&lt;br>&lt;i>#\"What have your learned about your role?\"#&lt;/i>&lt;br>
            &lt;i>#\"What has been your important success?\"#&lt;/i>&lt;br>Don\'t rake over past mistakes,
            don\'t focus on poor performance
            - you cannot change that, reserve those discussions future
            development - see below&lt;br>&lt;br>PRESENT&lt;br>Using open questions, help staff to identify
            their true strengths,
            capabilities, attributes, skills and attitudes. Create a
            comprehensive picture of them as a strategic contributor and
            resource.&lt;br>What are your skills, and to what level?&lt;br>&lt;i>#\"What have you added as
            capabilities over the past months?\"#&lt;/i>&lt;br>&lt;i>#\"What do you find are your
            most useful personal attributes in
            your role?\"#&lt;/i>&lt;br>&lt;br>FUTURE&lt;br>The future is the period where changes in
            capability and
            performance can be made.&lt;br>This discussion is where your people can figure out -
            with your
            help - what development they need to reach your performance
            standards and their career goals. It begins with understanding
            their career goals, so ....&lt;br>&lt;i>#\"What are your goals?\"#&lt;/i>&lt;br>&lt;i>#\"What
            development will be needed?\"#&lt;/i>
            &lt;br>&lt;i>#\"You have seen over the past months that you may need more skill in these
            areas .......................... what should we do about
            that?\"#&lt;/i>&lt;br>&lt;br>Finally: Agree a specific development plan that includes
            training/experience in the areas where more skill is needed. Fix dates
            in the diary&lt;br>&lt;br>The Manager\'s role is one of Mentor and Guide; not
            Judge and
            Jury</string>
    

    【讨论】:

    • 为了省去我们研究您所有代码的麻烦,您能否介绍一下您的方法?例如,哪个类是单例?另外,最后所有的 HTML 都是故意的吗?最后,请修正答案中的标记——请参阅stackoverflow.com/editing-help
    【解决方案3】:

    公共类 MidColorTextView 扩展 TextView { 私有字符串令牌; 私有静态上下文上下文; 私有字符串颜色跨度; 私有 int 颜色代码; 私有静态字体字体Arial;

    public MidColorTextView( Context context , AttributeSet attrs )
    {
        super(context, attrs);
    
        this.context = context;
    
    
        init();
    }
    
    private void init ()
    {
    
    
    
        setTypefaceArial ();
        setTypeface(getTypefaceArial ());
    
    }
    
    
    
    public int getColorCode ()
    {
        return colorCode;
    }
    
    public void setColorCode ( int colorCode )
    {
        this.colorCode = colorCode;
    }
    
    private CharSequence textContent;
    
    
    public static Typeface getTypefaceArial ()
    {
        return typefaceArial;
    }
    public static void setTypefaceArial ()
    {
        MidColorTextView.typefaceArial= Typeface.createFromAsset(context.getAssets(), "arial.ttf");
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      相关资源
      最近更新 更多