Markop
Markop

Reputation: 17

Android button doesn't change when pressed

I have a problem when i click on button it doesn't change the background image

this is the btn_states.xml

<item android:drawable="@drawable/btn_normal"/>
<item android:drawable="@drawable/btn_active" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_active" android:state_focused="true"/>

and activity_main.xml

 <Button
        android:id="@+id/button1"
        android:layout_width="250dp"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/btn_states"
        android:text="@string/app_name"
        android:textColor="#FFFFFF" />            

And the MainActivity.class

 final Button button1 = (Button) findViewById(R.id.button1);
    button1.setBackgroundResource(R.drawable.btn_states);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,
                    AboutActivity.class);
            startActivity(intent);
        }
    });

Upvotes: 0

Views: 236

Answers (1)

alanv
alanv

Reputation: 24114

The <selector> element, which inflates to a StateListDrawable, finds the most appropriate drawable for a given state set by linearly searching through a set of state specifications. It will select the first <item> that matches the state set.

In your example, the first <item> has no states specified, either inclusive (true) or exclusive (false), so it matches all state sets. As a result, the search will end early and the drawable for the first <item> will used for all possible state sets.

Instead, you could order it like this:

<selector>
    <item android:state_pressed="true"
          android:drawable="@drawable/btn_active" />
    <item android:state_focused="true"
          android:drawable="@drawable/btn_active" />
    <item android:drawable="@drawable/btn_normal" />
</selector>

Upvotes: 1

Related Questions