2017-08-15 34 views
0

私は、一連のデータを解析してlistViewに表示するアンドロイドアプリケーションを構築しています。ユーザーがそのデータセット内の単語を検索すると、その単語を強調表示します。androidのtextViewにハイライト文字列を表示する方法は?

問題は、検索語が最初に表示され、テキストビューが1行目を超えて表示されているが、段落の中間語の最後が強調表示されているが、その強調表示された語句をテキスト表示max line 1を使用してください。

テキストビューで文字列を調整して強調表示する方法はありますか?

答えて

0

必要なものは、スパンを使用することです。たとえば、次のようなテキストをハイライト表示することができます。

TextView textview = (TextView)findViewById(R.id.mytextview); 
Spannable spannable = new SpannableString("Hello World");   
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
textview.setText(spannable); 
0

すでにフラグメントを試してみる必要があります。これがあなたを助けることを望みます。

final TextView sampleText =(TextView)findViewById(R.id.tv_sample_text); 
EditText ed_texthere =(EditText)findViewById(R.id.ed_texthere); 

final String fullText = sampleText.getText().toString(); 

ed_texthere.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { 

    } 

    @Override 
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { 
     String typedText = charSequence.toString(); 
     if (typedText != null && !typedText.isEmpty()) { 
      int startPos = fullText.toLowerCase(Locale.US).indexOf(typedText.toLowerCase(Locale.US)); 
      int endPos = startPos + typedText.length(); 
      if (startPos != -1) { 
       Spannable spannable = new SpannableString(fullText); 
       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, startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
       sampleText.setText(spannable); 
      } else { 
       sampleText.setText(fullText); 
      } 
     } 
    } 

    @Override 
    public void afterTextChanged(Editable editable) { 

    } 
}); 
関連する問題