How to simulate pressed button in Android Studio when layout

Question:

How to simulate a pressed button in Android Studio when laying out without launching the application and without pressing the button? That is, I want to see immediately how the style of the button changes, depending on whether it is pressed or not, without launching the application itself?

Answer:

You can do this through styles. Adding colors:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffffff</color>
    <color name="darkwhite">#ffeeeeee</color>
    <color name="transparent">#00ffffff</color>
    <color name="semitransparent">#88000000</color>
    <color name="orange">#ffff8800</color>
    <color name="light_orange">#ffe27d18</color>
    <color name="light_blue">#ff00a2e8</color>
    <color name="black">#ff000000</color>
    <color name="menuButtonColor">#ffea8e44</color>
</resources>

Next, create a file in the drawable folder where it will be described that the button is pressed:

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

and then attach this drawable file to the button in xml:

<Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="58dp"
    android:text="how_it_works_button_title"
    android:background="@drawable/my_button_selector" />

Next, we look in the visual editor in Android Studio and adjust how it is necessary for our button to look.

UPDATE

In order to look at the pressed button, you need to end up with the following drawable file:

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

but then don't forget to remove the android:state_pressed="true" tag in one of the item so that the button has two states.

Scroll to Top