DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Cordova: Communicating Between JavaScript and Java
  • Why Software Development Leaders Should Invest in Continuous Learning and Growth Opportunities
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Reactive Event Streaming Architecture With Kafka, Redis Streams, Spring Boot, and HTTP Server-Sent Events (SSE)

Trending

  • Agile Estimation: Techniques and Tips for Success
  • Build a Digital Collectibles Portal Using Flow and Cadence (Part 1)
  • API Design
  • Freedom to Code on Low-Code Platforms
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Different way to handle events in Android

Different way to handle events in Android

Nilanchala Panigrahy user avatar by
Nilanchala Panigrahy
·
Sep. 01, 13 · Interview
Like (0)
Save
Tweet
Share
8.27K Views

Join the DZone community and get the full member experience.

Join For Free

Typically, events respond to user interactions. Android supports multiple ways to handle events on views. When a user clicks on an Android View, some method is getting called by the Android framework and then past the control to the application listeners.

For example, when a user clicks on a view like as a button, the onTouchEvent() method is called on that button object. In order to make our application respond to the event, we must extend the class and override the method. But extending every View object in order to handle such an event would not be practical. Each View class in Android provides a collection of nested interfaces called listeners with callbacks that you can much more easily define in order to handle the event.

1. Defining a listener programatically on the OnCreate method

button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        //do stuff
    }
});
?

This method will create an anonymous class for each button you create. This is recommended only if you have fewer listeners in your class. But if we have a complex screen layout with many views, then writing a listener programatically for each view will make the code messy. It's costly and less readable.

2. Setting the android:OnClick property in XML

?
<Button android:id="@+id/btnView"
    ...............
    ...............
    android:OnClick="btnViewOnClick"/>

Many people use this method of handling click events by writing an OnClick attribute in XML. But usually it is not preferable, because it is better to keep listeners inside the code. Internally, Android is using the Java reflection concept behind the scenes to handle this. It is less readable, and confuses some developers.

3. Implementing the OnClickListener interface on the Activity class and passing a reference to the Button


public class MainActivity extends Activity implements OnClickListener{
    @Override
    public void onClick(View v) {
        //do stuff
    }
 
    protected void onCreate(Bundle savedInstanceState) {
        ...
        button.setOnClickListener(this);
    } 
 				}

Here, we are implementing the OnClickListener interface on the activity class and passing a self reference to the button. This way, the OnClick listener will hold the reference to the activity object, and is a heavy operation to keep the whole activity’s object in it.

This way we can handle the click event for all views. However, we need to differentiate views using their IDs. We can use the view.getId() method to see which button was clicked. Again, this is preferable only when we have fewer views to handle. This way, all the click event handling codes are done in one place.

This way is hard to navigate because you can’t determine the type of the listener you are using with the current button (I know Eclipse will highlight the methods this is pointing at, but with lots of code I think it will be hard to find).

4. Create a field with the OnClickListener type

private OnClickListener onClickHandler = new OnClickListener(){
 
    @Override
    public void onClick(View v) {
        //stuff
    }
};
 
protected void onCreate(Bundle savedInstanceState) {
    ...
    button.setOnClickListener(onClickHandler);
}
?

The best practice is the create a local variable with the OnClickListener type. This way it is easy to navigate and more readable. But it doesn't stop you from implementing the other three options provided above. Everyone has different way of looking at the problem.

Event Android (robot)

Opinions expressed by DZone contributors are their own.

Related

  • Cordova: Communicating Between JavaScript and Java
  • Why Software Development Leaders Should Invest in Continuous Learning and Growth Opportunities
  • Building Real-Time Applications to Process Wikimedia Streams Using Kafka and Hazelcast
  • Reactive Event Streaming Architecture With Kafka, Redis Streams, Spring Boot, and HTTP Server-Sent Events (SSE)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: