【问题标题】:Selector doesn't work after change it programmatically选择器在以编程方式更改后不起作用
【发布时间】:2015-12-21 18:02:42
【问题描述】:

我有以下问题。我有一个具有不同颜色主题的应用程序。 在彩色布局的中间是一个带有白色角和白色文本的按钮。

按钮:

<Button
            android:id="@+id/button"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="50dp"
            android:background="@drawable/selector_button"
            android:layout_gravity="center"
            android:text="Button"
            android:textAllCaps="false"
            android:textSize="18sp"
          android:textColor="@color/buttontextcolor_green"
            />

选择器按钮:

<selector
    <item
        android:state_focused="true"
        android:state_pressed="false"
        android:drawable="@drawable/button_off" />
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/button_on" />
    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/button_on" />
    <item
        android:drawable="@drawable/button_off" />
</selector>

button_on/off 仅具有 stroke 和 solid 属性以使按钮在按下时完全变白。

问题在于 buttontextcolor_green:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item   android:state_focused="true"
        android:state_pressed="false"
        android:color="@color/md_white_1000" />

<item   android:state_focused="true"
        android:state_pressed="true"
        android:color="@color/greenPrimary"/>

<item   android:state_focused="false"
        android:state_pressed="true"
        android:color="@color/greenPrimary" />

<item   android:color="@color/md_white_1000" />

一切正常,我按下Button,按钮变为白色,按下时textcolor从白色变为绿色。

但在我以编程方式从按钮更改android:textColordrawable 后,它不会。

在我的问题开始时我很伤心,我使用多种颜色主题。因此,如果我按下按钮,那么我的Layoutbackgroundcolor 应该会更改,我也必须更改按钮的可绘制文本颜色。

lBackground.setBackgroundColor(getResources().getColor(R.color.bluePrimary));
button.setTextColor((getResources().getColor(R.color.buttontextcolor_blue)));

下一次,当我按下按钮时,textcolor 必须是蓝色的,但不是。每次点击时,textcolor 都会保持白色。只需在启动应用程序后第一次单击即可正常工作。

如果我的文字在语音上不正确,我深表歉意,我的德语更好!^^

问候

【问题讨论】:

  • 当您删除选择器并仅应用一种颜色 button.setTextColor((getResources().getColor(R.color.buttontextcolor_blue))); 这就是它不起作用的原因
  • buttontextcolor_blue 是一个 xml 文件,和 buttontextcolor_green 一样,只是在 item 属性中有其他颜色。
  • 但是我看到了问题,我不能使用颜色文件夹中的选择器?以前它位于可绘制文件夹中,但由于在 setTextColor 方法中使用可绘制,我得到了编译器错误。
  • 只使用getColorStateList

标签: android android-layout button text colors


【解决方案1】:

使用getColorStateList。它将解决您的问题。

换行button.setTextColor((getResources().getColor(R.color.buttontextcolor_blue)));

button.setTextColor(getResources().getColorStateList( R.color.buttontextcolor_blue)));

并将 buttontextcolor_blue color 放入颜色资源文件夹中,如 /res/color/buttontextcolor_blue.xml

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    相关资源
    最近更新 更多