2012-05-29 45 views

回答

21

是TextView的您的EditText和電視是TextView對象。使用下面的代碼:


public class MotivationalQuotesActivity extends Activity { 
    /** Called when the activity is first created. */ 

Button next; 
EditText et; 
TextView tv; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
    et = (EditText) findViewById(R.id.et); 
    tv = (TextView) findViewById(R.id.tv); 
    tv.setText("The name of our country is Bangladesh. Bangladesh is a land of rivers."); 

    next = (Button) findViewById(R.id.button1); 
    next.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       tv.setText("The name of our country is Bangladesh. Bangladesh is a land of rivers."); 
       String ett =et.getText().toString(); 
       String tvt =tv.getText().toString(); 

       int ofe = tvt.indexOf(ett,0); 
       Spannable WordtoSpan = new SpannableString(tv.getText()); 

     for(int ofs=0;ofs<tvt.length() && ofe!=-1;ofs=ofe+1) 
     {  


       ofe = tvt.indexOf(ett,ofs); 
        if(ofe == -1) 
         break; 
        else 
         {      

         WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
         tv.setText(WordtoSpan, TextView.BufferType.SPANNABLE); 
         } 


     } 


      } 
     }); 

    } 

} 

結果是:

enter image description here

+0

非常感謝你,你真的幫我做的項目.. – Mordiggian

+0

我有1個更多的問題,如何消除或重置亮點字? – Mordiggian

+1

如果你想消除突出顯示,你可以使用2種方法: **第一:**將原始文本設置爲TextView,例如「tv.setText(」我們國家的名稱是孟加拉國,孟加拉國是一片河流。 「);' **第二:**使用上面突出顯示的方法,但使用背景顏色(在這種情況下說**黑色**)作爲突出顯示的顏色,例如:'WordtoSpan.setSpan(new BackgroundColorSpan(color ),ofe + ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);' –

0

一個突出顯示文本的簡單快捷的方法,就是用字符串替換方法。更換的慾望字符串字體標籤

Spanned strHTML= Html.fromHtml("<center>"+full_string.replaceAll(strSrch,"<font color='yellow'>"+strSrch+"</font>")+"</center><br/>"); 
TextView tv=(TextView) v.findViewById(R.id.txtPager); 
tv.setText(strHTML,TextView.BufferType.SPANNABLE);