enjoinslip
enjoinslip

Reputation: 41

How to Toggle item from selector when a button is clicked in Android

I have the following for button

class MyButton(context: Context) : Button(context) {
    fun init(accessibilityUtil: AccessibilityUtil) {
        ...
        setBackgroundResource(R.drawable.button)
        ...
    }

    setOnClickListener{
         // some logic
    }

<selector xmlns:android="http://schemas.android.com/apk/res/android">
//alternate between these 2 items on each button click.
    <item android:state_pressed="false"
        android:state_focused="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
        </shape>
    </item>
    <item android:state_pressed="false"
        android:state_focused="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/black" />
        </shape>
    </item>
</selector>

Here, when button get's initialized, it has white background. What I want is when I click the button, the button should use item #2. When I press again, it should change back and use item #1.

ToggleButton is throwing some unrelated issues in regards to my button functionality. Can this be achieved just using Button and selector/item?

Upvotes: 0

Views: 31

Answers (1)

Gianluca Grasso
Gianluca Grasso

Reputation: 28

Yes, you can achieve toggle functionality using a button and a selector. Edit the XML by defining two separate items (one for each state):

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
    <shape android:shape="rectangle">
        <solid android:color="@color/white" />
    </shape>
</item>
<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <solid android:color="@color/black" />
    </shape>
</item>
</selector>

Modify your class to keep track of the current state and update the background:

class MyButton(context: Context) : Button(context) {
private var isPressed = false

init {
    setBackgroundResource(R.drawable.button)
    setOnClickListener {
        isPressed = !isPressed
        updateBackground()
        // Perform your logic here
    }
}

private fun updateBackground() {
    val backgroundRes = if (isPressed) {
        R.drawable.selec_item_2
    } else {
        R.drawable.selec_item_1
    }
    setBackgroundResource(backgroundRes)
}

}

Make sure to replace the IDs in this sample code with the appropriate resources for your selector items.

Upvotes: 0

Related Questions