频道栏目
首页 > 资讯 > Android > 正文

Android开发中 自动适应字体大小的EditText

17-12-05        来源:[db:作者]  
收藏   我要投稿

Android 自动适应字体大小的EditText

Android 中 EditText 单行显示时,如果字体过多,自动缩小字体,在字号小于指定字号时,显示”…” ,具体请参考如下代码:

  1. packagecom.zepp.newsports.ui.widget;
  2.  
  3. importandroid.content.Context;
  4. importandroid.content.res.TypedArray;
  5. importandroid.graphics.Canvas;
  6. importandroid.graphics.Color;
  7. importandroid.graphics.Rect;
  8. importandroid.text.TextPaint;
  9. importandroid.text.TextUtils;
  10. importandroid.util.AttributeSet;
  11. importandroid.widget.TextView;
  12. importcom.zepp.newsports.R;
  13. importcom.zepp.z3a.common.util.FontUtil;
  14.  
  15. /**
  16. *CreatedbyQYon15/7/20.
  17. */
  18. publicclassAutoStretchTextViewextendsTextView{
  19. privatefloatDEFAULT_MIN_TEXTSIZE=28;
  20. privateStringTAG=AutoStretchTextView.class.getSimpleName();
  21. privateRectviewRect;
  22. privateinttextColor=Color.LTGRAY;
  23. privatebooleancenterHorization;
  24. privatebooleanalignLeft;
  25.  
  26. publicAutoStretchTextView(Contextcontext){
  27. super(context);
  28. }
  29.  
  30. publicAutoStretchTextView(Contextcontext,AttributeSetattrs){
  31. super(context,attrs);
  32. init(attrs);
  33. }
  34.  
  35. publicAutoStretchTextView(Contextcontext,AttributeSetattrs,intdefStyleAttr){
  36. super(context,attrs,defStyleAttr);
  37. init(attrs);
  38. }
  39.  
  40. @OverrideprotectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
  41. setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),MeasureSpec.getSize(heightMeasureSpec));
  42. }
  43.  
  44. @OverrideprotectedvoidonDraw(Canvascanvas){
  45. intlayoutWidth=getWidth();
  46. doublecharWidth=0;
  47. intheight=getHeight();
  48. TextPaintpaint=getPaint();
  49. Stringtext=getText().toString();
  50. viewRect=newRect();
  51.  
  52. floatdrawedWidth=paint.measureText(text);
  53. char[]textCharArray=text.toCharArray();
  54. if(textCharArray.length>0){
  55. paint.getTextBounds(textCharArray,0,textCharArray.length,viewRect);
  56. charWidth=paint.measureText(textCharArray,textCharArray.length-1,1);
  57. }
  58.  
  59. while(layoutWidth-drawedWidth<>
  60. if(getTextSize()<=DEFAULT_MIN_TEXTSIZE){
  61. StringBuilderbuilder=newStringBuilder();
  62. for(charchars:textCharArray){
  63. builder.append(chars);
  64. floatvisibleTextWidth=paint.measureText(builder.toString()+“…”);
  65. if(layoutWidth-visibleTextWidth<1.5*charWidth){
  66. text=builder.append(”…”).toString();
  67. char[]chars1=text.toCharArray();
  68. paint.getTextBounds(chars1,0,chars1.length,viewRect);
  69. break;
  70. }
  71. }break;
  72. }
  73. paint.setTextSize(getTextSize()-1);
  74. drawedWidth=paint.measureText(text);
  75. if(textCharArray.length>0)
  76. charWidth=paint.measureText(textCharArray,textCharArray.length-1,1);
  77. }
  78.  
  79.  
  80. floatstartY=height-(height-viewRect.height())*0.5f;
  81. paint.setColor(textColor);
  82. if(centerHorization){
  83. canvas.drawText(text,Math.abs(layoutWidth-viewRect.width())/2,startY,paint);
  84. }elseif(alignLeft){
  85. canvas.drawText(text,5,startY,paint);
  86. }else{
  87. intstartX=layoutWidth-viewRect.width();
  88. if(startX<0)
  89. startX=0;
  90. canvas.drawText(text,startX,startY,paint);
  91. }
  92. }
  93.  
  94. privatevoidinit(AttributeSetattrs){
  95. if(!isInEditMode()){
  96.  
  97. Stringresource=attrs.getAttributeValue(”http://schemas.android.com/apk/res/android”,“textColor”);
  98. if(!TextUtils.isEmpty(resource)){
  99. if(resource.contains(“@”)){
  100. textColor=getContext().getResources().getColor(Integer.valueOf(resource.substring(1,resource.length())));
  101. }else{
  102. textColor=Color.parseColor(resource);
  103. }
  104. }
  105.  
  106. TypedArraytypedArray=
  107. getContext().obtainStyledAttributes(attrs,R.styleable.AutoStretchTextView);
  108. DEFAULT_MIN_TEXTSIZE=
  109. typedArray.getDimension(R.styleable.AutoStretchTextView_default_min_textsize,
  110. DEFAULT_MIN_TEXTSIZE);
  111. typedArray.recycle();
  112. intfont=attrs.getAttributeIntValue(“http://schemas.android.com/apk/res-auto”,“font”,
  113. 0);
  114. getPaint().setTypeface(FontUtil.getInstance().getFontTypeface(getContext(),font));
  115.  
  116. centerHorization=
  117. attrs.getAttributeBooleanValue(”http://schemas.android.com/apk/res-auto”,
  118. ”centerHorization”,false);
  119. alignLeft=
  120. attrs.getAttributeBooleanValue(”http://schemas.android.com/apk/res-auto”,
  121. ”alignLeft”,false);
  122. }
  123. }
  124.  
  125.  
  126. }
    package com.zepp.newsports.ui.widget;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Rect;
    import android.text.TextPaint;
    import android.text.TextUtils;
    import android.util.AttributeSet;
    import android.widget.TextView;
    import com.zepp.newsports.R;
    import com.zepp.z3a.common.util.FontUtil;
    
    /**
     * Created by QY on 15/7/20.
     */
    public class AutoStretchTextView extends TextView {
        private float DEFAULT_MIN_TEXTSIZE = 28;
        private String TAG = AutoStretchTextView.class.getSimpleName();
        private Rect viewRect;
        private int textColor = Color.LTGRAY;
        private boolean centerHorization;
        private boolean alignLeft;
    
        public AutoStretchTextView(Context context) {
            super(context);
        }
    
        public AutoStretchTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(attrs);
        }
    
        public AutoStretchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(attrs);
        }
    
        @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
        }
    
        @Override protected void onDraw(Canvas canvas) {
            int layoutWidth = getWidth();
            double charWidth = 0;
            int height = getHeight();
            TextPaint paint = getPaint();
            String text = getText().toString();
            viewRect = new Rect();
    
            float drawedWidth = paint.measureText(text);
            char[] textCharArray = text.toCharArray();
            if (textCharArray.length > 0) {
                paint.getTextBounds(textCharArray, 0, textCharArray.length, viewRect);
                charWidth = paint.measureText(textCharArray, textCharArray.length - 1, 1);
            }
    
            while (layoutWidth - drawedWidth < charWidth) {
                if (getTextSize()  <= DEFAULT_MIN_TEXTSIZE) {
                    StringBuilder builder = new StringBuilder();
                    for (char chars : textCharArray) {
                        builder.append(chars);
                        float visibleTextWidth = paint.measureText(builder.toString() + "...");
                        if (layoutWidth - visibleTextWidth < 1.5 * charWidth) {
                            text = builder.append("...").toString();
                            char[] chars1 = text.toCharArray();
                            paint.getTextBounds(chars1, 0, chars1.length, viewRect);
                            break;
                        }
                    } break;
                }
                paint.setTextSize(getTextSize() - 1);
                drawedWidth = paint.measureText(text);
                if(textCharArray.length > 0)
                    charWidth = paint.measureText(textCharArray, textCharArray.length - 1, 1);
            }
    
    
            float startY = height -(height- viewRect.height()) * 0.5f;
            paint.setColor(textColor);
            if (centerHorization) {
                canvas.drawText(text, Math.abs(layoutWidth - viewRect.width()) / 2 , startY, paint);
            } else if (alignLeft) {
                canvas.drawText(text, 5, startY, paint);
            } else {
                int startX = layoutWidth - viewRect.width();
                if (startX < 0)
                    startX = 0;
                canvas.drawText(text, startX, startY, paint);
            }
        }
    
        private void init(AttributeSet attrs) {
            if (!isInEditMode()) {
    
                String resource = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "textColor");
                if (!TextUtils.isEmpty(resource)) {
                    if (resource.contains("@")) {
                        textColor = getContext().getResources().getColor(Integer.valueOf(resource.substring(1, resource.length())));
                    } else {
                        textColor = Color.parseColor(resource);
                    }
                }
    
                TypedArray typedArray =
                        getContext().obtainStyledAttributes(attrs, R.styleable.AutoStretchTextView);
                DEFAULT_MIN_TEXTSIZE =
                        typedArray.getDimension(R.styleable.AutoStretchTextView_default_min_textsize,
                                DEFAULT_MIN_TEXTSIZE);
                typedArray.recycle();
                int font = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto", "font",
                        0);
                getPaint().setTypeface(FontUtil.getInstance().getFontTypeface(getContext(), font));
    
                centerHorization =
                        attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto",
                                "centerHorization", false);
                alignLeft =
                        attrs.getAttributeBooleanValue("http://schemas.android.com/apk/res-auto",
                                "alignLeft", false);
            }
        }
    
    
    }
    

    在 attr.xml中设置自定义的属性,用于设置最小字体,绘制字体是居中或巨左,默认是居右绘制的

    [html] view plain copy print?
    1.  
    2.  
    3. 
      
          
              
              
              
          
      
      

相关TAG标签
上一篇:Android自定义View实现搜索动画效果
下一篇:javascript之异常捕获代码实例
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站