Roger_88
Roger_88

Reputation: 477

Selector not working on click button effect

I would like to change the background color of an itemviewholder when its clicked. To that I tried to use "selector" and "state_pressed" on it but is not working.

In this test code I tried to do that with a button and a linearlayout just to test. I'm doing this way because in my real code the itemviewholder will be inside of a LinearLayout. The button is just to test too. I'm using API 16.

Why is not working(when I click on the button or on the linearlayout nothing happens) and how can I fix this?

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

drawable/item_effect.xml

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- default -->
    <item android:drawable="@color/colorAccent"/>

    <!-- pressed -->
    <item android:state_pressed="true"
        android:drawable="@color/colorPrimaryDark"/>

</selector>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/item_effect"></LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/item_effect"/>

</RelativeLayout>

MainActivity.java

package br.com.roger.selectortest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Upvotes: 1

Views: 500

Answers (1)

Napster
Napster

Reputation: 1373

I believe it's because of your selector and how it's set up. The default item in the selector needs to be the last one. Try

<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- pressed -->
    <item android:state_pressed="true"
        android:drawable="@color/colorPrimaryDark"/>

    <!-- default -->
    <item android:drawable="@color/colorAccent"/>
</selector>

Upvotes: 3

Related Questions