text处理 替换图片 高亮 等 EditText监听器 注意

来源:互联网 发布:淘宝编辑软件 编辑:程序博客网 时间:2024/04/29 07:25

EditText:

  通常用于显示文字,但有时候也需要在文字中夹杂一些图片,比如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;      }  

以上实际都是Html.fromHtml(html)的代码实现形式。

=============================================================================

TextView: (方法与EditView类似)

如何让一个TextView中的关键字高亮显示? 

/** * 关键字高亮显示 * @param target 需要高亮的关键字 */ public void highlight(String target){ String temp=getText().toString(); SpannableStringBuilder spannable = new SpannableStringBuilder(temp); CharacterStyle span=null; Pattern p = Pattern.compile(target); Matcher m = p.matcher(temp); while (m.find()) { span = new ForegroundColorSpan(Color.RED);//需要重复!
//span = new ImageSpan(drawable,ImageSpan.XX);//设置现在图片 spannable.setSpan(span, m.start(), m.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } setText(spannable); }
复制代码










使用EditText的addTextChangedListener(new TextWatcher())方法

 在使用EditText的addTextChangedListener(new TextWatcher())方法时(即给EditText增加监听器):

注意:

  1、在使用里面的函数时,不能没有条件的改变本EditText的内容 , 因为这样容易引起死循环,所以必须要加限制条件

////////////////////////////////////////////////////
  //给EditText增加监听器
  contentEditText.addTextChangedListener(new TextWatcher() {
   
   int l=0;////////记录字符串被删除字符之前,字符串的长度
   int location=0;//记录光标的位置
   @Override
   public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    
   }
   
   @Override
   public void beforeTextChanged(CharSequence s, int start, int count,
     int after) {
    // TODO Auto-generated method stub
    l=s.length();
    location=contentEditText.getSelectionStart();
   }
   
   @Override
   public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    if (l>s.toString().length()) {
     gyf.function.face_analysis faceAnalysis=new gyf.function.face_analysis(releaseComment.this);
     SpannableStringBuilder sBuilder=faceAnalysis.getSpannableStringBuilder(s.toString());
     //eText.setText(sBuilder);
     //eText.setText("");
     contentEditText.setText(sBuilder);
     Editable etable=contentEditText.getText();
     Selection.setSelection(etable, location);
     //Toast.makeText(releaseComment.this, "11111", Toast.LENGTH_SHORT).show();
     
    }


    //Toast.makeText(releaseComment.this, "0000", Toast.LENGTH_SHORT).show();
   }
  });

2、每次刷新EditText时,光标也会跟着重置,即位置跑到了开头

   如上代码所示。

   有关光标的介绍有:

提起Android的EditText的光标选择问题,可以通过android.text.Selection包提供的方法来实现,Android SDK提供了有关光标选择的多种方法,比如说getSelectionEnd、getSelectionStart、removeSelection、 selectAll、setSelection,详细的参数声明如下

final static int  getSelectionEnd(CharSequence text)Return the offset of the selection edge or cursor, or -1 if there is no selection or cursor.final static int  getSelectionStart(CharSequence text)Return the offset of the selection anchor or cursor, or -1 if there is no selection or cursor.final static void  removeSelection(Spannable text)Remove the selection or cursor, if any, from the text.final static void  selectAll(Spannable text)Select the entire text.final static void  setSelection(Spannable text, int index)Move the cursor to offset index.static void  setSelection(Spannable text, int start, int stop)Set the selection anchor to start and the selection edge to stop.



Android123提示大家,从上面的参数来看,可以发现Spannable类型,常规我们的EditText中的编辑中Editable直接实现Spannable接口,所以我们可以通过下面的方法来设置选择:

  1.   Editable ea= etEdit.getText();  //etEdit为EditText
  2.   Selection.setSelection(ea, ea.length()-1); // Android开发网提示这里ea的长度必须大于1。否则会有异常发生

原创粉丝点击