android TextView和EditText中显示图片

EditText(TextView同样处理)。 
添加图片主要用SpannableString和ImageSpan类:

       Drawable drawable = getResources().getDrawable(R.drawable.icon);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        SpannableString spannable = new SpannableString(getText(R.id.editText1).toString() + "[smile]");
        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
         spannable.setSpan(span, getText(R.id.editText1).length(),getText(R.id.editText1).length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        editText.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;  
    } 


你可能感兴趣的:(android,String,null)