Highlight Textview Using EditText(使用 EditText 突出显示 Textview)
问题描述
我目前正在为 android 制作一个类似应用程序的搜索引擎,我想突出显示从 edittext 到 textview 的搜索词...这是我到目前为止,它只突出显示 textview 中的第一个词
Im currently making a search engine like application for android and i want to highlight the searched word from edittext to textview... this is that i got so far and it only highlights the first word in the textview
TV.setText("Hello World", TextView.BufferType.SPANNABLE);
Spannable WordtoSpan = (Spannable) TV.getText();
WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), 0, notes.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(WordtoSpan);
推荐答案
我认为您想突出显示用户在 EditText 中键入的 TextView 的特定单词.说 et 是您的 EditText 并且 tv 是 TextView 对象.使用以下代码:
I think you want to highlight a specific word of TextView which user types in a EditText. Say et is your EditText and tv is TextView object. Use the following code:
String ett =et.getText().toString();
String tvt =tv.getText().toString();
int index = tvt.indexOf(ett);
Spannable WordtoSpan = new SpannableString( tv.getText() );
if(index != -1)
{
WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), index, index+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
else
tv.setText("The name of our country is Bangladesh");
<小时>
结果如下:
Here is the outcome:
完整代码如下:
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");
next = (Button) findViewById(R.id.button1);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String ett =et.getText().toString();
String tvt =tv.getText().toString();
int index = tvt.indexOf(ett);
Spannable WordtoSpan = new SpannableString( tv.getText() );
if(index != -1)
{
WordtoSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), index, index+ett.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(WordtoSpan, TextView.BufferType.SPANNABLE);
}
else
tv.setText("The name of our country is Bangladesh");
}
});
}
}
这篇关于使用 EditText 突出显示 Textview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 EditText 突出显示 Textview
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01