matparrott
matparrott

Reputation: 1

Simulating a button press with another button press

I currently want to have a button that when I press it another button flashes as if it has been pressed at the same time and activates the function of the other button. My current code is as such:

fun onTwo(view: View) {
            button1.callOnClick()
            button1.isPressed = true
                    }

However the issue I am facing is that it freezes button1 as if it is pressed until it is pressed again. Anyone have a solution for this?

Upvotes: 0

Views: 84

Answers (3)

matparrott
matparrott

Reputation: 1

I ended up fixing this issue using coroutines in the end as such:

fun onTwo(view: View){
                GlobalScope.async{
                    delay(100)
                    button1.isPressed = false
                    GlobalScope.cancel()
                }
                button1.setPressed(true)
                button1.performClick()

            }

Upvotes: 0

Jay
Jay

Reputation: 11

Try performClick() method like below:

fun onTwo(view: View) 
{
    button1.performClick()
}

Upvotes: 0

Animesh Sahu
Animesh Sahu

Reputation: 8096

You could add listener in one of the button to check for clicks and then use that event to trigger click event in another button, like this:

val button1 = findViewById(R.id.btn1ID) as Button
button1.setOnClickListener {
    val button2 = findViewById(R.id.btn2ID) as Button
    button2.performClick()
}

Replace R.id.btn1ID and R.id.btn2ID with their respective id(a).

Reference: performClick()


You could also create a utility function to use it without making redundant variables like this:

@Suppress("UNCHECKED_CAST")  
fun Activity.findButtonById(@IdRes res : Int) : Button =
    findViewById(res) as Button

// and then in your create method of activity:
findButtonById(R.id.btn1ID).setOnClickListener {
    findButtonById(R.id.btn2ID).performClick()
}

Upvotes: 1

Related Questions