ant2009
ant2009

Reputation: 22486

Cannot change focus/state for button png using selector element

Android Studio 0.3.7

Hello,

I have created 2 buttons png and patched using draw9patch. The buttons will indicate whether the buttons is pressed or unpressed.

I have the following buttons_colours.xml in my values directory

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/rd_btn_press"/> <!-- pressed -->

    <item android:state_focused="true"
       android:state_pressed="false"
       android:drawable="@drawable/rd_btn"/>        <!-- unpressed -->

    <!-- Default -->
    <item android:drawable="@drawable/rd_btn"/>

</selector>

In my layout for the button I have this:

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/rd_btn"/>

Problem 1: I get an element selector must be declared in my buttons_colours.xml

Problem 2: Not sure if this is related to problem 1, but the button never changes to my rd_btn_press state when I press it.

Many thanks for any suggestions,

Upvotes: 0

Views: 1147

Answers (1)

mihail
mihail

Reputation: 2173

you have set wrong background for the button. Replace @drawable/rd_btn with `buttons_colours :

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start"
    android:id="@+id/button"
    android:layout_gravity="center_horizontal"
    android:background="@drawable/buttons_colours"/>

also, I don't know why you have two states in your items in the selector. Here an example of working selector:

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

Upvotes: 1

Related Questions