2012-05-29 21 views

Trả lời

21

Say et này là EditText và tv là đối tượng TextView. Sử dụng đoạn mã sau:


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); 
         } 


     } 


      } 
     }); 

    } 

} 

Kết quả là:

enter image description here

+0

cảm ơn bạn rất nhiều, bạn thực sự giúp tôi với dự án của mình .. – Mordiggian

+0

Tôi có thêm 1 câu hỏi, cách xóa hoặc đặt lại đánh dấu trong từ? – Mordiggian

+1

Nếu bạn muốn xóa đánh dấu, bạn có thể sử dụng 2 phương pháp: ** Đầu tiên: ** Đặt văn bản thô thành TextView như 'tv.setText (" Tên quốc gia của chúng tôi là Bangladesh. Bangladesh là vùng đất của các con sông. ");" ** Thứ hai: ** Sử dụng phương pháp làm nổi bật ở trên nhưng sử dụng màu nền (giả sử ** màu đen ** trong trường hợp này) làm màu nổi bật như: 'WordtoSpan.setSpan (new BackgroundColorSpan (color) .black), ofe, ofe + ett.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ' –

0

Một cách dễ dàng và nhanh chóng làm nổi bật một văn bản, là sử dụng chuỗi thay thế phương pháp. Thay thế chuỗi mong muốn bằng thẻ phông chữ

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);