Android - 按钮的选择器在工具栏中时不起作用

Android - Button's selector does not working when in toolbar

我正在尝试将选择器设置为包含在工具栏中的按钮。选择器在设置为工具栏外部的按钮时起作用。有帮助吗?

工具栏

   <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/light_red"
    android:elevation="4dp"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="4dp">

        <ImageButton
            android:id="@+id/btnSync"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:background="@drawable/sync"
            android:layout_centerVertical="true"
            android:layout_margin="10dp"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>


</android.support.v7.widget.Toolbar>

选择器

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/sinchronize_q" android:state_focused="true" />
    <item android:drawable="@drawable/sinchronize" />

</selector>

问题出在你的drawable,特别是这部分

android:state_focused="true"

您的 ImageButton 没有获得焦点,因为它被其父视图或某些 EditText 视图占用。通常 state_focused 在 drawables 中使用不多, 将其更改为 state_pressed 它会起作用所以这就是你需要的

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/sinchronize_q"
      android:state_pressed="true"/>
<item android:drawable="@android:drawable/sinchronize"/>

如果您想确保您的项目没有获得焦点,您可以将 android:focusableInTouchMode="true" 添加到您的 ImageButton