2014-05-01 67 views
5

我有一個TextView,我正在尋找允許用戶搜索特定的字符串。如果找到字符串,它應該突出顯示。使用背景跨度太慢且尷尬,所以我想弄清楚是否可以讓它選擇字符串。我知道EditText這可能會使用setSelection(),但我不希望用戶能夠編輯文本,同時仍然可以手動突出顯示文本,但我似乎無法使用EditText進行管理。有沒有什麼辦法可以編程方式選擇TextView中的文本?

我想,那麼它是一個或者;是要麼可能以編程方式選擇文本TextView可能允許文本選擇而不允許在EditText編輯?

注意:我實際上使用了一個自定義視圖來擴展TextView,所以我假設它不是EditText;我只是不確定哪個(如果有的話)會起作用。

+0

這將有可能改變的TextView的字符串的一部分顏色。只需在零件周圍使用一些HTML標記並在setText中使用HTML.fromHTML即可。或者你可以使用Spannable對象。 –

+0

是的,這正是我原來所做的,但由於文本很大,所以速度很慢。 – yuttadhammo

+1

「使用背景範圍太慢而且很尷尬」 - 嗯...真的嗎?我沒有看到這個問題。通過[示例項目](https://github.com/commonsguy/cw-omnibus/tree/master/RichText/Search),我可以搜索更長字符串中子字符串的出現次數,刪除所有現有的「BackgroundColorSpans」和在〜20行代碼中,在20-30ms內應用新的BackgroundColorSpans。 「文字很大」 - 多大? – CommonsWare

回答

0

不確定問題是否仍然存在,我會提供我的解決方案。也許會對來自搜索引擎的人有用。

因此,我的理解是,選擇TextView中的所有文本而不能修改其內容。我沒有檢查它是否對非常大的文本有效,但希望不那麼糟糕。

請注意,API版本應該是> = 11

import android.annotation.TargetApi; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Build; 
import android.text.Selection; 
import android.text.Spannable; 
import android.util.AttributeSet; 

public class SelectableTextView extends TextView 
{ 
    public SelectableTextView(Context context) 
    { 
     super(context); 
     init(); 
    } 

    public SelectableTextView(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
     init(); 
    } 

    public SelectableTextView(Context context, AttributeSet attrs, int defStyleAttr) 
    { 
     super(context, attrs, defStyleAttr); 
     init(); 
    } 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public SelectableTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) 
    { 
     super(context, attrs, defStyleAttr, defStyleRes); 
     init(); 
    } 

    private void init() 
    { 
     if (Build.VERSION.SDK_INT > 10) 
      setTextIsSelectable(true); 
    } 

    @Override 
    public boolean onTextContextMenuItem(int id) 
    { 
     switch (id) 
     { 
      case android.R.id.cut: 
       return true; 

      case android.R.id.paste: 
       return true; 

      case android.R.id.shareText: 
      { 
       String selectedText = getText().toString().substring(getSelectionStart(), getSelectionEnd()); 

       if (selectedText != null && !selectedText.isEmpty()) 
       { 
        Intent sendIntent = new Intent(); 
        sendIntent.setAction(Intent.ACTION_SEND); 
        sendIntent.putExtra(Intent.EXTRA_TEXT, selectedText); 
        sendIntent.setType("text/plain"); 
        sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        getContext().startActivity(sendIntent); 
       } 

       return true; 
      } 

      case android.R.id.selectAll: 
      { 
       selectAllText(); 
       return true; 
      } 
     } 

     return super.onTextContextMenuItem(id); 
    } 

    public void selectAllText() 
    { 
     if (Build.VERSION.SDK_INT > 10) 
      Selection.setSelection((Spannable) getText(), 0, length()); 
    } 

}

相關問題