2015-12-23 121 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); 
     } 
    } 
} 
相关问题