Two button click example

In this example we are going to do some stuff with two buttons. The trick is clicking them both simultaneously, holding them, and after some time some action to happen. So the scenario goes: Hold the buttons for 1 second and after that make some Toast message for successful notation.

NOTE: We are going to use EventBus for this example.
For those who dont know what it is, here is some useful links:
EventBus by GreenRobot Library

NOTE: We are going to use ButterKnife Library also for binding the Views from the XML, like buttons, text views, edit text etc.
ButterKnife by Jake Wharton Library with examples

Lets get in to some code samples.

First make MainClass where we can start our application and add the buttons.

On top of the class we declare the buttons as ButtonOne & ButtonTwo. Next we need some boolean values on class level so we can adjust their values dinamicly ass the buttons are clicked. In the onCreate method we instantiate two objects. The first one is Runnable which is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.The Runnable Interface requires of the class to implement the method run(), where we want our event to be started. Second one is Handler. A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
So, we are going to use our Runnable and Handler so we can run, and handle our two buttons click. We use our pressDelay long, for time we want the clicks on the buttons to be delayed. After our declared 1 second, the toast message will be shown.

Next is the Event Handler to be created. EventBus crash course: Event is registered and listens when something happens. It trigers the event handler, and with @Subscribe annotation we catch that event and display our message.

As you can see, its empty class, or empty event handler. We need only to catch the event, not to send some data trough.

After the two clicks are cached, handler delayed the action, runnable starts the event and the event is cached, we use our isNextActivityStarted boolean to set to true so we the event (in our case the message) is not started twice.

Spread the love

Leave a Reply

Your email address will not be published.