如何在ListView中突出显示搜索结果

时间:2014-11-12 19:26:08

标签: android search highlight

我不明白如何突出搜索结果。

我试图在SpannableString之类的mTextView.setText(spannable)的帮助下做到这一点,但我不知道如何在我的情况下实现它。 在行中写入错误 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); // Listview Data final String[] products = new String[] { getResources().getString(R.string.t1_2), getResources().getString(R.string.t1_3), getResources().getString(R.string.t1_4), }; lv = (ListView) findViewById(R.id.list_view); inputSearch = (EditText) findViewById(R.id.inputSearch); mTextView = (TextView) findViewById(R.id.product_name); // Adding items to listview adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.product_name, products); lv.setAdapter(adapter); lv.setVisibility(View.GONE); // Once user enters a new data in EditText we need to get the text from // it and passing it to array adapter filter. inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changed the Text Search.this.adapter.getFilter().filter(cs); textlength = inputSearch.getText().length(); // adapter.clear(); if (textlength != 0) { lv.setVisibility(View.VISIBLE); for (int i = 0; i < products.length; i++) { if (textlength <= products[i].length()) { Spannable spannable = new SpannableString(inputSearch.getText().toString()); ColorStateList blueColor = new ColorStateList(new int[][] { new int[] {}}, new int[] { Color.BLUE }); TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null); spannable.setSpan(highlightSpan, 0,5 , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTextView.setText(spannable); } } } } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } }); } }

{{1}}

0 个答案:

没有答案