突出显示通过EditText搜索的所有单词

时间:2012-05-29 13:01:23

标签: android textview android-edittext highlight

你好我想知道如何突出显示在EditText中输入的所有单词并将出现在TextView中这篇文章与这篇文章有关Highlight Textview Using EditText

2 个答案:

答案 0 :(得分:21)

et 是您的EditText, tv 是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

答案 1 :(得分:0)

突出显示文本的一种简单快捷的方法是使用字符串替换方法。用字体标记

替换所需的字符串
func canRotate() -> Void {}

extension UIApplication {

  class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
    if let nav = base as? UINavigationController {
       return topViewController(base: nav.visibleViewController)
    }
    if let tab = base as? UITabBarController {
      if let selected = tab.selectedViewController {
         return topViewController(base: selected)
      }
    }
    if let presented = base?.presentedViewController {
        return topViewController(base: presented)
    }
    return base
}