android - AppCompat下如何设置SearchView的光标颜色

标签 android android-appcompat android-styles

我的 SearchView 是 android.support.v7.widget.SearchView 和 AppTheme 如下所示。

<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/color_accent</item>
</style>

<style name="AppTheme" parent="AppBaseTheme">
</style>

SearchView 的颜色看起来很奇怪,光标和底线显示为白色,并快速转换为强调色,如何处理?我想让光标和底线保持白色。

最佳答案

经过大量的实验,我终于能够通过使用 autoCompleteTextViewStyle 属性以及自定义光标 Drawable 来更改光标颜色。修改您在示例中提供的代码,您将执行以下操作。首先,您将上述属性添加到您的主题中,如下所示:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/color_accent</item>
    <item name="autoCompleteTextViewStyle">@style/cursorColor</item>
</style>

然后为“cursorColor”创建样式,该样式将引用您将创建的光标Drawable(下一步):

<style name="cursorColor" parent="Widget.AppCompat.AutoCompleteTextView">
        <item name="android:textCursorDrawable">@drawable/cursor</item>
</style>

最后要做的是创建将用作替换光标的可绘制光标(cursor.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#FFFFFF" />
    <size android:width="1dp" />
</shape>

这是光标分别在应用新主题之前和之后的样子...

之前

enter image description here

之后

enter image description here

最后一点,您始终可以通过修改 Drawable 中的相应字段来更改新光标的宽度和颜色:

<!-- Change this to increase the width -->
<size android:width="1dp"/>
<!-- Change this to change the color -->
<solid android:color="#FFFFFF" />

关于android - AppCompat下如何设置SearchView的光标颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730253/

相关文章:

android - 如何在 Android 4.0 中使用 Android 5+ 的 ProgressBar

从 R.attr 引用返回颜色资源 ID 的 Android 测试方法

android - Github 中的 Google Maps Api key 代码

java - 如果 ArrayMap 或 SparseArray 中的键散列存在冲突怎么办?

android - 我可以使用 PhoneGap 或其他 API 将视频上传到我的服务器吗?

Android VideoView 方向随缓冲视频的变化

android - 如何在 Xamarin.Forms 中显示 "up"/"back"按钮?

android - setCompoundDrawableTintList 的向后兼容解决方案

android - 样式不适用于自定义复选框和单选按钮

android - 如何在 android 中更改 DatePicker 的样式?