在Android中更改突出显示文本的颜色

时间:2010-08-10 16:48:38

标签: android

我不确定这是可能的,也许有人可以帮我。我在Android应用程序中有一个EditText视图,在蓝色背景上有白色文本。选择文本后(通过长按和编辑对话框),我希望突出显示为白色,并将文本颜色更改为黑色。令人讨厌的是,似乎没有办法在高亮上设置文本的颜色。您可以使用 textColorHighlight 设置高光颜色,但不能设置文本颜色,因此使用白色文本设置白色高光会产生较大的白色块。

看起来你应该在xml中以声明方式做一些微不足道的事情,但是虽然我尝试了很多样式和颜色的组合,但我无法改变颜色。

检查其他标准应用程序似乎文本颜色似乎永远不会改变所以我认为这是不容易做到的事情。我宁愿不必将EditText子类化,如果可能只是为了这么简单。我错过了什么吗?可以在视图xml中完成吗?

5 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

尝试:<item name="android:textColorHighlight">your_color</item>

以你作为主题的风格。 例如,

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="colorPrimary">your_color1</item>
    <item name="colorPrimaryDark">your_color2</item>
    <item name="colorAccent">your_color3</item>
    <item name="android:textColor">your_color4/item>
    <item name="android:textColorHighlight">your_color</item>
</style>

然后使用此样式作为清单文件中活动的主题。例如 -

<activity
    android:name=".youractivity"
    android:label=""
    android:theme="@style/AppTheme.NoActionBar"       
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

答案 2 :(得分:0)

正如this所提到的那样,您应该使用选择器来更改文本颜色,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Pressed State -->
    <item android:state_pressed="true"
        android:color="#FFFFFF" />

    <!-- Focused State -->
    <item android:state_focused="true"
        android:color="#FFFFFF" />

    <!-- Default State -->
    <item android:color="#000000" />
</selector>

然后将 textColor 属性设置为 @ drawable / selector_name

答案 3 :(得分:0)

尝试使用textColorHighlight - “突出显示文本的颜色”。 http://developer.android.com/reference/android/R.attr.html#textColorHighlight

答案 4 :(得分:0)

Object mSelectionForegroundColorSpan;
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    super.onSelectionChanged(selStart, selEnd);
    if(mSelectionForegroundColorSpan == null){
        mSelectionForegroundColorSpan = new ForegroundColorSpan(Color.GREEN);
    }else{
        getText().removeSpan(mSelectionForegroundColorSpan);
    }
    if(selStart > selEnd){
        int swap = selStart;
        selStart = selEnd;
        selEnd = swap;
    }
    getText().setSpan(mSelectionForegroundColorSpan, selStart, selEnd, Spanned.SPAN_INTERMEDIATE);
}

覆盖 TextView onSelectionChanged方法,获取文字并设置ForegroundColorSpan

enter image description here

相关问题