Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

android - Highlight All Words that is searched via EditText

Hello I want to know how to highlight all Words that is inputted in the EditText and will appear in the TextView this post is related to this one Highlight Textview Using EditText

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Say et is your EditText and tv is TextView object. Use the following code:


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


        }  


            }
        });

    }

}

The result is:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...