android TextView 之探究

來源:互聯網
上載者:User

標籤:

1:插入圖片替換

  

//代碼  mSubjectDetailView = (TextView) findViewById(R.id.subject_detail);                CharSequence text = "★,dsfdsfdddd,如果fdsfs★東東";        SpannableStringBuilder builder = new SpannableStringBuilder(text);        String rexgString = "★";        Pattern pattern = Pattern.compile(rexgString);        Matcher matcher = pattern.matcher(text);        while (matcher.find()) {            builder.setSpan(                    new ImageSpan(this, R.drawable.ic_launcher), matcher.start(), matcher                            .end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        }        mSubjectDetailView.setText(builder);//布局檔案<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <TextView        android:id="@+id/my_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="@string/hello_world" />     <TextViewandroid:id="@+id/subject_detail"android:layout_width="match_parent"android:layout_height="wrap_content"android:minHeight="50dp"android:gravity="center_vertical"android:text="subject"android:textColor="@android:color/primary_text_light_nodisable"android:background="@android:color/white"android:textSize="25sp" /></RelativeLayout>

 :

 

2:另外的一種TextView 裡加入圖片

    public void setChips(){        if(getText().toString().contains(",")) // check comman in string        {                        SpannableStringBuilder ssb = new SpannableStringBuilder(getText());            // split string wich comma            String chips[] = getText().toString().trim().split(",");            int x =0;            // loop will generate ImageSpan for every country name separated by comma            for(String c : chips){                // inflate chips_edittext layout                 LayoutInflater lf = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);                TextView textView = (TextView) lf.inflate(R.layout.chips_edittext, null);                textView.setText(c); // set text                int image = ((ChipsAdapter) getAdapter()).getImage(c);                textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, image, 0);                // capture bitmapt of genreated textview                int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);                textView.measure(spec, spec);                textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());                Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(),Bitmap.Config.ARGB_8888);                Canvas canvas = new Canvas(b);                canvas.translate(-textView.getScrollX(), -textView.getScrollY());                textView.draw(canvas);                textView.setDrawingCacheEnabled(true);                Bitmap cacheBmp = textView.getDrawingCache();                Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);                textView.destroyDrawingCache();  // destory drawable                // create bitmap drawable for imagespan                BitmapDrawable bmpDrawable = new BitmapDrawable(viewBmp);                bmpDrawable.setBounds(0, 0,bmpDrawable.getIntrinsicWidth(),bmpDrawable.getIntrinsicHeight());                // create and set imagespan                 ssb.setSpan(new ImageSpan(bmpDrawable),x ,x + c.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                x = x+ c.length() +1;            }            // set chips span             setText(ssb);            // move cursor to last             setSelection(getText().length());        }                    }

 

 3:android SpannableStringBuilder實現圖文混排

spannableStringBuilder 用法詳解:     SpannableString ss = new SpannableString("紅色打電話斜體刪除線綠色底線圖片:.");               //用顏色標記文本             ss.setSpan(new ForegroundColorSpan(Color.RED), 0, 2,                       //setSpan時需要指定的 flag,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前後都不包括).                     Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //用超連結標記文本             ss.setSpan(new URLSpan("tel:4155551212"), 2, 5,                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //用樣式標記文本(斜體)             ss.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7,                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //用刪除線標記文本             ss.setSpan(new StrikethroughSpan(), 7, 10,                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //用底線標記文本             ss.setSpan(new UnderlineSpan(), 10, 16,                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //用顏色標記             ss.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 13,                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);             //擷取Drawable資源             Drawable d = getResources().getDrawable(R.drawable.icon);               d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());             //建立ImageSpan             ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);             //用ImageSpan替換文本             ss.setSpan(span, 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);               txtInfo.setText(ss);             txtInfo.setMovementMethod(LinkMovementMethod.getInstance()); //實現文本的滾動      通常用於顯示文字,但有時候也需要在文字中夾雜一些圖片,比如QQ中就可以使用表情圖片,又比如需要的文字高亮顯示等等,如何在android中也做到這樣呢?     記得android中有個android.text包,這裡提供了對文本的強大的處理功能。     添加圖片主要用SpannableString和ImageSpan類:               Drawable drawable = getResources().getDrawable(id);              drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());              //需要處理的文本,[smile]是需要被替代的文本              SpannableString spannable = new SpannableString(getText().toString()+"[smile]");              //要讓圖片替代指定的文字就要用ImageSpan              ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);              //開始替換,注意第2和第3個參數表示從哪裡開始替換到哪裡替換結束(start和end)             //最後一個參數類似數學中的集合,[5,12)表示從5到12,包括5但不包括12              spannable.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);                setText(spannable);  
將需要的文字高亮顯示:     public void highlight(int start,int end){              SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());//用於可變字串              ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);              spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              setText(spannable);          }              加底線:     public void underline(int start,int end){              SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());              CharacterStyle span=new UnderlineSpan();              spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              setText(spannable);          }              組合運用:    SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());              CharacterStyle span_1=new StyleSpan(android.graphics.Typeface.ITALIC);              CharacterStyle span_2=new ForegroundColorSpan(Color.RED);              spannable.setSpan(span_1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              spannable.setSpan(span_2, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              setText(spannable);  
案例:帶有\n分行符號的字串都可以用此方法顯示2種顏色/**          * 帶有\n分行符號的字串都可以用此方法顯示2種顏色          * @param text          * @param color1          * @param color2          * @return          */         public SpannableStringBuilder highlight(String text,int color1,int color2,int fontSize){              SpannableStringBuilder spannable=new SpannableStringBuilder(text);//用於可變字串              CharacterStyle span_0=null,span_1=null,span_2;              int end=text.indexOf("\n");              if(end==-1){//如果沒有分行符號就使用第一種顏色顯示                  span_0=new ForegroundColorSpan(color1);                  spannable.setSpan(span_0, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              }else{                  span_0=new ForegroundColorSpan(color1);                  span_1=new ForegroundColorSpan(color2);                  spannable.setSpan(span_0, 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                  spannable.setSpan(span_1, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                                     span_2=new AbsoluteSizeSpan(fontSize);//字型大小                  spannable.setSpan(span_2, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);              }              return spannable;          }

 

 

 

用到的相關方法:

1:textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, image, 0); 

    源碼:

         

public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) {        final Resources resources = getContext().getResources();        setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null,                top != 0 ? resources.getDrawable(top) : null,                right != 0 ? resources.getDrawable(right) : null,                bottom != 0 ? resources.getDrawable(bottom) : null);    }


 

2:ssb.setSpan(new ImageSpan(bmpDrawable),x ,x + c.length() , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//插入Obj的位置

 

android TextView 之探究

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.