Belial
Belial

Reputation: 668

How to change color of button when pressed if it already have shape_layout? Android

I want to change color of button when pressed, but for it I already have

android:background="@drawable/shape_layout"

shape_layout.xml code:

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

    <gradient android:startColor="#ff055500"
              android:endColor="#ff055500"/>

    <corners android:radius="1dp" />

    <stroke android:width="1px" android:color="#ffffff" />

</shape>

So how to make a change color of button when pressed?

Upvotes: 1

Views: 2236

Answers (2)

Blacklight
Blacklight

Reputation: 3827

You will need to create a selector-drawable:

shape_selector.xml

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

  <item android:state_pressed="true" android:drawable="@drawable/shape_layout_pressed"/>
  <item android:state_focused="true" android:drawable="@drawable/shape_layout_focused"/>
  <item android:drawable="@drawable/shape_layout"/>
</selector>

Add the desired color for pressed/focused state to new XML-drawables, and set the selector-drawable as the background: android:background="@drawable/shape_selector"

Upvotes: 3

dafilipaj
dafilipaj

Reputation: 1074

You will need two more XML files:

  • shape_layout_hover.xml (basically same file, just change color to one that should be displayed on pressed state)
  • selector file that will select one of those two layouts on different button states.

Example of selector XML:

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

    <item android:state_pressed="true" android:drawable="@drawable/shape_layout_hover" />

    <item android:state_focused="true" android:drawable="@drawable/shape_layout_hover" />

    <item android:drawable="@drawable/shape_layout" />
</selector>

Afterwards create button style with selector file as background. And set that style to button item.

<item name="android:background">@drawable/button_selector</item>

Upvotes: 2

Related Questions