android TextView相关属性及文本处理

来源:互联网 发布:惠普q1910更新软件 编辑:程序博客网 时间:2024/05/18 23:53

textview 设置图片两种方式:

         TextView textView=null;
1,        int flagResId = getResources().getIdentifier("icon", "drawable", getPackageName());
           textView.setCompoundDrawablesWithIntrinsicBounds(flagResId, 0, 0, 0);

2,   Drawable drawable = mContext.getResources().getDrawable(R.drawable.shop_arrow_down);
          drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
          textView.setCompoundDrawables(null, null, drawable, null);
         
         
TextView控件的背景透明度和字体透明度

方式1,
tv.setBackgroundColor(Color.argb(255, 0, 255, 0)); //背景透明度  
tv.setTextColor(Color.argb(255, 0, 255, 0));   //文字透明度
方式2,
tv.setTextColor(0xffff00ff);
0xffff00ff是int类型的数据,分组一下0x|ff|ff00ff,0x是代表颜色整数的标记,ff是表示透明度,ff00ff表示颜色,注意:这里ffff00ff必须是8个的颜色表示
原理,把透明度转换为色值。就是根据透明度转换为色值,放在前两位      

[java] view plain copy
  1. 透明度转换可以参照下表:  
  2. 透明度 对应十六进制  
  3. 100%    ff  
  4. 90% e6  
  5. 85% d9  
  6. 80% cc  
  7. 70% b3  
  8. 6099  
  9. 5080  
  10. 4066  
  11. 30% 4d  
  12. 2033  
  13. 1526  
  14. 10% 1a  
  15. 5%  0d  
  16. 0%  00  

one textView different text style

 String s= "Hello Everyone";

 SpannableString ss1=  new SpannableString(s);
 ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size
 ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color
 TextView tv= (TextView) findViewById(R.id.textview);
 tv.setText(ss1); 

//设置字体大小(绝对值,单位:像素)
//        msp.setSpan(new AbsoluteSizeSpan(20), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        msp.setSpan(new AbsoluteSizeSpan(20,true), 6, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //第二个参数boolean dip,如果为true,表示前面的字体大小单位为dip,否则为像素,同上。
//        //设置字体大小(相对值,单位:像素) 参数表示为默认字体大小的多少倍
//        msp.setSpan(new RelativeSizeSpan(0.5f), 8, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示默认字体大小的一半
//        msp.setSpan(new RelativeSizeSpan(2.0f), 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //2.0f表示默认字体大小的两倍
//        msp.setSpan(new ForegroundColorSpan(Color.MAGENTA), 12, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色
//        msp.setSpan(new BackgroundColorSpan(Color.CYAN), 15, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置背景色为青色


textView.setText(Html.fromHtml("<b>myLogin</b> <i>logout</i>"));SpannableString styledString = new SpannableString("myLogin logout");

styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, 7, 0);
styledString.setSpan(new StyleSpan(Typeface.ITALIC), 8, 14, 0);
tv.setText(styledString);


计算字体宽度:
public static float GetTextWidth(String text, float Size) {
        TextPaint FontPaint = new TextPaint();
        FontPaint.setTextSize(Size);
        return FontPaint.measureText(text);
    }        
    
    // 计算文本,行数,高度
FontMetrics fm = mTextView.getPaint().getFontMetrics();
mFontHeight = (int) (Math.ceil(fm.descent - fm.top) + 2);// 获得每行高度   
mPageLineNum = (int) (mTextHeight / mFontHeight);// 获得行数

//TextView 分页设置相关
getLineBounds(int line, Rect bounds) // 得到指定行的边界
只要从第一行开始一行一行往下看, 直到找到超出边界的那一行, 就能知道这个 TextView 能显示多少行了.
或者用 getHeight() / getLineHeight() 也能获取 TextView 的最大显示行数

getLineForVertical(int vertical) // 根据纵坐标得到对应的行号
getLineEnd(int line) // 返回指定行中最后一个字在整个字符串中的位置


一个TextView设置多种颜色文字
Html.fromHtml(String.format(formate, getColorText(params, color)));


[java] view plain copy
  1. public class ReadView extends TextView {  
  2.    
  3.     // 构造函数略...  
  4.    
  5.     @Override  
  6.     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  7.         super.onLayout(changed, left, top, right, bottom);  
  8.         resize();  
  9.     }  
  10.    
  11.     /** 
  12.      * 去除当前页无法显示的字 
  13.      * @return 去掉的字数 
  14.      */  
  15.     public int resize() {  
  16.         CharSequence oldContent = getText();  
  17.         CharSequence newContent = oldContent.subSequence(0, getCharNum());  
  18.         setText(newContent);  
  19.         return oldContent.length() - newContent.length();  
  20.     }  
  21.    
  22.     /** 
  23.      * 获取当前页总字数 
  24.      */  
  25.     public int getCharNum() {  
  26.         return getLayout().getLineEnd(getLineNum());  
  27.     }  
  28.    
  29.     /** 
  30.      * 获取当前页总行数 
  31.      */  
  32.     public int getLineNum() {  
  33.         Layout layout = getLayout();  
  34.         int topOfLastLine = getHeight() - getPaddingTop() - getPaddingBottom() - getLineHeight();  
  35.         return layout.getLineForVertical(topOfLastLine);  
  36.     }  
  37. }  

//TextView设置完setMaxLines后,通过TextView.getHeight方法获取的是当前行数的高度,而非文字完全显示的高度
//实际获取高度方法

[java] view plain copy
  1. /** 
  2.     *  
  3.     * @param pTextView 
  4.     * @return 
  5.     */  
  6.    private int getTextViewHeight(TextView pTextView) {    
  7.        Layout layout = pTextView.getLayout();    
  8.        int desired = layout.getLineTop(pTextView.getLineCount());    
  9.        int padding = pTextView.getCompoundPaddingTop() + pTextView.getCompoundPaddingBottom();    
  10.        return desired + padding;    
  11.    }    

//自定义View绘制文本时,格式化文本内容StaticLayout实现:
     public void onDraw(Canvas canvas){ 
            super.onDraw(canvas); 
            TextPaint tp = new TextPaint();
            tp.setColor(Color.BLUE);
            tp.setStyle(Style.FILL);
            tp.setTextSize(50);
            String message = "paint,draw paint指用颜色画,如油画颜料、水彩或者水墨画,而draw 通常指用铅笔、钢笔或者粉笔画,后者一般并不涂上颜料。两动词的相应名词分别为p";
            StaticLayout myStaticLayout = new StaticLayout(message, tp, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            myStaticLayout.draw(canvas);
            canvas.restore();
        } 
        
 自定义view绘制文本计算文本宽度高度:
[java] view plain copy
  1. private Rect mBounds = new Rect();  
  2.  String text = String.valueOf(mCount);    
  3.        mPaint.getTextBounds(text, 0, text.length(), mBounds);    
  4.        float textWidth = mBounds.width();    
  5.        float textHeight = mBounds.height();    
  6.        canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2  + textHeight / 2, mPaint);   


文本分割处理

[java] view plain copy
  1. /** 
  2.      * 自动分割文本 
  3.      * @param content 需要分割的文本 
  4.      * @param p  画笔,用来根据字体测量文本的宽度 
  5.      * @param width 最大的可显示像素(一般为控件的宽度) 
  6.      * @return 一个字符串数组,保存每行的文本 
  7.      */  
  8.     public static String[] autoSplitText(String content, Paint p, int width) {  
  9.   
  10.         float textWidth = p.measureText(content);  
  11.         if(textWidth <= width) {  
  12.             return new String[]{content};  
  13.         }  
  14.   
  15.         int length = content.length();  
  16.         int start = 0, end = 1, i = 0;  
  17.         int lines = (int) Math.ceil(textWidth / width); //计算行数  
  18.         String[] lineTexts = new String[lines];  
  19.   
  20.         while(start < length) {  
  21.             if(p.measureText(content, start, end) > width) { //文本宽度超出控件宽度时  
  22.                 lineTexts[i++] = content.substring(start, end);//(String) content.subSequence(start, end);  
  23.                 start = end;  
  24.             }  
  25.             if(end == length) { //不足一行的文本  
  26.                 lineTexts[i] = content.substring(start, end);//(String) content.subSequence(start, end);  
  27.                 break;  
  28.             }  
  29.             end += 1;  
  30.         }  
  31.         return lineTexts;  
  32.     }  

TextView字体间距

1、Android:lineSpacingExtra
设置行间距,如”3dp”。
2、android:lineSpacingMultiplier
设置行间距的倍数,如”1.2″。

设置texview 垂直滚动条
  android:focusable="true"
android:focusableInTouchMode="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:scrollbars="vertical"        
        android:singleLine="false"


设置textview 文字水平自动滚动(跑马灯效果)
<com.example.playpic.MyTextView
        android:id="@+id/myTv"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#000000"
        
        android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
        />

布局文件需添加属性:android:addStatesFromChildren="true"
修改的textview

[java] view plain copy
  1. public class MyTextView extends TextView {    
  2.         
  3.         public MyTextView(Context context) {    
  4.             super(context);    
  5.         }    
  6.             
  7.         public MyTextView(Context context, AttributeSet attrs) {    
  8.             super(context, attrs);    
  9.         }    
  10.             
  11.         public MyTextView(Context context, AttributeSet attrs, int defStyle) {    
  12.             super(context, attrs, defStyle);    
  13.         }    
  14.             
  15.         @Override    
  16.         protected void onDraw(Canvas canvas) {    
  17.             super.onDraw(canvas);    
  18.         }    
  19.         @Override    
  20.         public boolean isFocused() {    
  21.             return true;    
  22.         }    
  23.         
  24.     }    

setContentView(R.layout.scrollview1);  
            MyTextView tv=(MyTextView)findViewById(R.id.myTv);  
            tv.setText(str);  
            tv.setMovementMethod(ScrollingMovementMethod.getInstance());  


android 动态设置TextView值,例:金额增加 

[java] view plain copy
  1. public static void autoIncrement(final TextView target, final float start,    
  2.                final float end, long duration) {    
  3.        
  4.            ValueAnimator animator = ValueAnimator.ofFloat(start, end);    
  5.        
  6.            animator.addUpdateListener(new AnimatorUpdateListener() {    
  7.                private FloatEvaluator evalutor = new FloatEvaluator();    
  8.                private DecimalFormat format = new DecimalFormat("####0.0#");    
  9.        
  10.                @Override    
  11.                public void onAnimationUpdate(ValueAnimator animation) {    
  12.        
  13.                    float fraction = animation.getAnimatedFraction();    
  14.                    float currentValue = evalutor.evaluate(fraction, start, end);    
  15.                    target.setText(format.format(currentValue));    
  16.                }    
  17.            });    
  18.            animator.setDuration(duration);    
  19.            animator.start();    
  20.        
  21.        }      



Textview 设置maxLines>1时,超出部分内容没...省略号解决方法

解决方案:1,自定义实现,2,通过post(Runable r)即在Textview设置文字后显示完计算处理

[java] view plain copy
  1. class OmitTextViewDeal implements Runnable{  
  2.        TextView tv;  
  3.        String txt;  
  4.        public GoodsAttributeTextViewDeal(){  
  5.   
  6.        }  
  7.        @Override  
  8.        public void run() {  
  9.            float txtLen=tv.getPaint().measureText(txt);  
  10.            int tvLen=tv.getWidth();  
  11.            int lines=Math.round(txtLen/tvLen+0.9f);  
  12.   
  13.            if(lines>2){  
  14.                String[] splitContent= UtilsView.autoSplitText(txt,tv.getPaint(),tvLen);  
  15.                String ts=splitContent[1].substring(0,splitContent[1].length()-5);  
  16.                String showTxt=splitContent[0]+ts+"...";  
  17.                tv.setText(showTxt);  
  18.            }  
  19.        }  
  20.    }  
  21.   
  22. public static String[] autoSplitText(String content, Paint p, int width) {  
  23.   
  24.        float textWidth = p.measureText(content);  
  25.        if(textWidth <= width) {  
  26.            return new String[]{content};  
  27.        }  
  28.   
  29.        int length = content.length();  
  30.        int start = 0, end = 1, i = 0;  
  31.        int lines = (int) Math.ceil(textWidth / width); //计算行数  
  32.        String[] lineTexts = new String[lines];  
  33.   
  34.        while(start < length) {  
  35.            if(p.measureText(content, start, end) > width) { //文本宽度超出控件宽度时  
  36.                lineTexts[i++] = content.substring(start, end);//(String) content.subSequence(start, end);  
  37.                start = end;  
  38.            }  
  39.            if(end == length) { //不足一行的文本  
  40.                lineTexts[i] = content.substring(start, end);//(String) content.subSequence(start, end);  
  41.                break;  
  42.            }  
  43.            end += 1;  
  44.        }  
  45.        return lineTexts;  
  46.    }  

使用:

tv_attr.setText(txtAttr);
                OmitTextViewDeal attrTvDeal=new OmitTextViewDeal();
                attrTvDeal.tv=tv_attr;
                attrTvDeal.txt=txtAttr;
                holder.tv_attr.post(attrTvDeal);

原创粉丝点击