You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在主题切换时修改AutocompleteSupportFragment选中地点的文本颜色

解决AutocompleteSupportFragment深色模式下文本颜色问题

问题原因

AutocompleteSupportFragment内部输入框的默认文本颜色未跟随自定义的@color/text变量,导致深色模式下选中地点后文本仍显示为黑色,与主题预期不符。

解决方案

方法一:全局主题配置(推荐)

通过修改应用主题,让所有AutocompleteSupportFragment自动适配主题文本颜色:

  1. 在res/values/styles.xml中添加自动完成输入框的自定义样式:
<style name="AutocompleteTextViewStyle" parent="Widget.Places.AutocompleteTextView">
    <item name="android:textColor">@color/text</item>
    <item name="android:textColorHint">@color/hint</item>
</style>
  1. 在应用主题Theme.UserApp中引入该样式:
<style name="Theme.UserApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- 保留原有主题属性 -->
    <item name="placesAutocompleteTextViewStyle">@style/AutocompleteTextViewStyle</item>
</style>

该配置会让输入框文本颜色自动继承@color/text的取值,适配浅色/深色主题切换。

方法二:直接设置输入框颜色(快速生效)

在初始化AutocompleteSupportFragment后,找到内部输入框并手动设置颜色:

// 初始化完成后添加以下代码
EditText editText = autocompleteSupportFragmentPick.getView()
    .findViewById(com.google.android.libraries.places.R.id.places_autocomplete_search_input);
if (editText != null) {
    editText.setTextColor(ContextCompat.getColor(requireContext(), R.color.text));
}

注意:需使用Places库内部的输入框ID,避免控件查找失败。

方法三:给Fragment单独设置主题

在布局文件中为Fragment指定自定义主题,限定文本颜色规则:

  1. 创建Fragment专属主题:
<style name="AutocompleteFragmentTheme" parent="@style/Theme.UserApp">
    <item name="android:textColor">@color/text</item>
    <item name="android:textColorHint">@color/hint</item>
</style>
  1. 修改布局中的Fragment标签:
<fragment
    android:id="@+id/autocompletePickLoc"
    android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="8dp"
    android:theme="@style/AutocompleteFragmentTheme"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/pickUpIndicator"
    app:layout_constraintTop_toBottomOf="@+id/txtPickup" />

验证效果

完成配置后切换到深色主题,选中地点后输入框文本会自动变为@color/text对应的白色,与提示文字颜色保持统一。

内容的提问来源于stack exchange,提问作者Ajinkya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:13:17