2015-12-23 147 views
1

當用戶選擇複製粘貼的文本時,如何更改突出顯示的文本的文本顏色。更改突出顯示的文本顏色



在此圖像中我想文字

世界

的顏色由黑色變爲白色。我怎樣才能做到這一點?

我嘗試添加ColorStateList作爲drawable,但它沒有幫助。 我的TextView:

<TextView 
    android:id="@+id/tv_hello" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    android:textColorHighlight="@color/light_blue" 
    android:textIsSelectable="true"/> 

回答

1

在res目錄中創建顏色文件夾。然後添加這個XML文件。讓我們text_color_change.xml

RES /顏色/ text_color_change.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:state_selected="true" android:color="#444"/> 
    <item android:state_focused="true" android:color="#444"/> 
    <item android:state_pressed="true" android:color="#444"/> 
    <item android:color="#ccc"/> 

</selector> 

然後在TextView中,添加文字顏色爲上述文件。

<TextView 
    .... 
    android:textColor="@color/text_color_change" /> 
+0

這給所選文本bg。我已經添加了這個。我想改變突出顯示的文本的'textColor'。 –

+0

我已經嘗試過,但不幸的是,這也無法正常工作。 –

1

添加此屬性選擇屬性,選擇的項目將保持它的顏色狀態,直到別的選擇。 在

selector.xml添加本

 <!-- Activated -->  
<item 
    android:state_activated="true" 
    android:color="#ff0000" /> 

     <!-- Active -->  
<item 
    android:state_active="true" 
    android:color="#ff0000" /> 

檢查this瞭解更多詳情。

+0

我已經嘗試過,但不幸的是,這也無法正常工作。 –

+0

你是對的,它會改變選擇的顏色。但問題是它改變了整個textView textColor,因爲我只想改變選定的textColor。 –

2

你的資源內/彩色文件夾中創建一個名爲text_color_selector.xml文件

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:state_pressed="true" android:color="#d48383"/> 
    <item android:state_pressed="false" android:color="#121212"/> 
    <item android:state_selected="true" android:color="#d48383"/> 
    <item android:state_focused="true" android:color="#d48383"/> 

</selector> 

那麼你的TextView中設置此爲:

android:textColor="@color/text_color_selector" 
+0

我已經嘗試過,但不幸的是,這也無法正常工作。 –

1

我不知道這是可能沒有做它自己:

public class MyTextView extends TextView { 

    ... Constructors, ... 

    private ForegroundColorSpan mSpan = new ForegroundColorSpan(0xffff0000); 

    @Override 
    public void setText(CharSequence text, BufferType type) { 
     // make sure the text is spannable 
     if (type == BufferType.NORMAL) { 
      type = BufferType.SPANNABLE; 
     } 
     super.setText(text, type); 
    } 

    @Override 
    protected void onSelectionChanged(int selStart, int selEnd) { 
     super.onSelectionChanged(selStart, selEnd); 

     Spannable txt = (Spannable) getText(); 

     // ok even if not currently attached 
     txt.removeSpan(mSpan); 

     if (selStart != selEnd) { 
      txt.setSpan(mSpan, selStart, selEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     } 
    } 
} 
相關問題