在我工作的大型应用程序上,有一个具有某种颜色背景的Activity,这与我们对插入符号和文本选择句柄和底线非常相似。这就是为什么我将“colorControlActivated”颜色设置为白色(设计师决定使用这种颜色)。
Activity还有一个对话框,它有一个EditText,但没有这个特殊的背景,所以好像是EditText的插入符号,文本选择句柄和底线 - 都不存在。 / p>
那是因为“colorControlActivated”是在Activity的样式中设置的,正如我所注意到的,不能设置为特定的EditText。
如果我没有设置它,对话框中的EditText看起来没问题,但不是其他地方的(带背景)。
为了使这个问题变得简单,我在同一个Activity布局上只询问了2个EditText。
以下是此问题的2个屏幕截图:
默认选择颜色:
白色选择颜色:
我尝试为每个EditText设置不同的样式,但是我失败了。我还尝试手动扩充EditText(我在原来的大型应用程序中做了),使用ContextThemeWrapper和每个的不同样式,但它似乎也没有工作。我还尝试从应用程序上下文创建LayoutInflater。
没有人帮助过。
以下是我尝试执行测试的示例项目代码:
activity_main.xml中
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"
tools:context="com.example.user.myapplication.MainActivity">
<FrameLayout
android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#008678"
android:paddingBottom="10dp" android:paddingTop="10dp">
<EditText
android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"
android:hint="put text here"
android:text="some text to select in similar color of default selection color"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f4f4f4"
android:paddingBottom="10dp" android:paddingTop="10dp">
<EditText
android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"
android:hint="put text here" android:text="some text to select in almost white color background"/>
</FrameLayout>
</LinearLayout>
styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorControlActivated">#fff</item>
</style>
</resources>
MainActivity没有什么特别的东西,但默认的东西(setContentView ...)。
请注意,实际上,对话框的背景为白色,因此插入符号等根本不明显。我只是在这里改变它,以便你看到问题。
如何让2个EditTexts的插入符号(以及文本选择句柄和底线)颜色不同?
回到原始代码(这里没有写),是否有一种简单的方法可以使它适用于对话框,这样EditText就会有一个不同于插入符号的插入颜色。托管它的活动?
答案 0 :(得分:1)
使用spans。
示例:
final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");
// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158));
// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
yourTextView.setText(sb);
编辑:此处描述了一个很好的解决方案:https://stackoverflow.com/a/4897379/1378564