Tuesday , September 21 2021

Event Handling in Android using Interface Type

Event Handling in Android using Interface Type – In Java, we can use an interface like a Type or Class and reference context of any instance of the class in which the interface is implemented.

Event Handling in Android using Interface Type
Event Handling in Android using Interface Type

This functionality of Java Interface allows us to register an Event Source with its Event Listener.

Under this method we create an Anonymous Event Listener Class that has no name and assigns the reference of that Unnamed or Noname Class to the Variable of an Appropriate Listener Interface Type. Then through that Variable, register the Event Source with the Anonymous Listener Class.

In this way too, all the processes of Event Handling are internally similar to the method discussed in the previous section, but when seen from outside, there is a difference between the two methods.

Apart from the process of creating Anonymous Event Listener Class and registering the Event Source with it, there is no difference in how to implement the Callback Event Handler Method and under Interface Type, this Callback Method is also defined in the same manner as Exactly The way in which the Nested Listener Class was defined in the previous section.

When we define an Event Listener Class as Member Method that implements the Appropriate Listener Interface and then we need to register the Event Source with that Event Listener Class, as we highlighted in the following statement the Event Listener Class Let’s create an Anonymous Object that binds the Event Source with the Event Listener Class –

findViewById(R.id.btnAdd).setOnClickListener(new ClickHandler()); findViewById(R.id.btnSub).setOnClickListener(new ClickHandler()); findViewById(R.id.btnMul).setOnClickListener(new ClickHandler()); findViewById(R.id.btnDiv).setOnClickListener(new ClickHandler()); findViewById(R.id.btnRem).setOnClickListener(new ClickHandler());

In this way also, the Create Event Listener Object has to be created only for One Time Use, whose total work is so that it can register the Event Source with the Event Listener Class so that the Event Source will fire The Listner class from Events can notify and execute the Callback Event Handler Method as a Response and therefore this Object is not saved as a Named Object.

But when we want to register an Event Source on an Event Listener Class using Interface Type, then we do not create an Anonymous Object of the Event Listener Class but instead create an Event Listener Class as an Anonymous Class and this Anonymous Defining the Callback Event Handler Method of Appropriate Event Listener Interface in Event Listener Class results in event Listener Interface Implementation.

So now we can Assign the reference of this Anonymous Event Listener Class to the Variable of the Event Listener Interface Type which has been implemented in that Anonymous Event Listener Class. Because the Variable of Interface Type can only hold a reference to a class when all its Abstract Methods have been implemented in that Class and in our example only one named onClick () in the Interface named View.OnClickListener. Method, which is implemented in the Anonymous Event Listener Class.

In this way, now if we want to register the Event Source to the Anonymous Event Listener Class using the Interface Type method, then we have to specify the Variable of the Listener Interface Type which contains the Anonymous Event Listener Class as highlighted in the following statement. Reference Stored-

findViewById(R.id.btnAdd).setOnClickListener(clickHandler); findViewById(R.id.btnSub).setOnClickListener(clickHandler); findViewById(R.id.btnMul).setOnClickListener(clickHandler); findViewById(R.id.btnDiv).setOnClickListener(clickHandler); findViewById(R.id.btnRem).setOnClickListener(clickHandler);

Whereas we can define the Anonymous Event Listener Class as follows in which the onClick () Callback Event Handler Method of View.OnClickListener Interface is Implemented, which gets executed as Response via Notify from Events fired by Event Source. –

    private View.OnClickListener clickHandler = new View.OnClickListener (){         public void onClick(View btnClicked) {              . . .         }     };

At the beginning of this code, we have used private Keyword as it is an Event Handler and Event Handler is only useful for handling events fired by Layouts of Current Activity. So there is no point specifying it with public or default Access Specifier.

Because we are creating a Variable Create View.OnClickListener Interface Type named clickHandler, so it can only be Assigned as a Reference to the Instance of the same Class as Value, in which all Abstract Methods Declared in View.OnClickListener Interface are implemented. Be define.

Since we have not yet created such a class, either we create a class in which the View.OnClickListener Interface is implanted and then Assign the clickHandler Variable from any of its instances, as in the previous section as Member Listener Class. Or we create an Anonymous class in which the onClick () Abstract Method of View.OnClickListener Interface is implemented and at the same time create a new instance of that Created Class and assign its reference to clickHandler Variable, as The above code is done in Fragement.

When we use this second method, the above Code Fragement is firstly Highlighted Program Code Execute as follows, through the Specified View.OnClickListener () Constructor in the Right Side of the Assignment Operator and create an Unnamed or Anonymous Event Listener Class This is because the priority of Assignment Operator is the lowest and Specified Parenthesis with View.OnClickListener () Constructor has the highest priority-

private View.OnClickListener clickHandler = new View.OnClickListener (){         public void onClick(View btnClicked) {              . . .         }     };

Since this Anonymous Event Listener Class has no name, as soon as this class is created, it is necessary to create an instance of it, otherwise as soon as this Highlighted Code Block is executed, Program Control will proceed, it will be Newly Defined for Compiler. Anonymous Class will be Inaccessible. As a result, the Garbage Collector of Java will destroy it and free its resources because no space is allocated to a class in memory by the Java Compiler until it creates an instance.

That is why, as soon as the Anonymous Class is created by the above Highlighted Code, the “new” operator does his work and creates an instance of this Newly Created Anonymous Class.

Since the priority of the “new” operator is lower than the parenthesis, the new operator starts its work only after the View.OnClickListener () Constructor is created in response to the execution of the Create Anonymous Class and a Newly Defined Anonymous Event Listener Class Create Instance and return its reference which gets assigned in the ClickHandler Variable of View.OnClickListener Interface Type.

Another thing to note here is that while in this code we are defining an Anonymous class, but this whole class is defining as a single statement and in Java each statement ends with a Semicolon. That is why despite specifying the description of an Anonymous Class, after the Closing Curly Brace of the Anonymous Class, we have finished the statement using Semicolon whereas when creating a Normal Java Class, Semicolon is never used after the Closing Curly Brace.

Now if we modify our previous example using another method of Event Handling Mechanism through Interface Type, then the code of our Modified Java File will be as follows-

File NameMainActivity.java

package com.bccfalna.arithmetic;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Register Event Source Using View.OnClickListener Interface Type clickHandler variable
        findViewById(R.id.btnAdd).setOnClickListener( clickHandler );
        findViewById(R.id.btnSub).setOnClickListener( clickHandler );
        findViewById(R.id.btnMul).setOnClickListener( clickHandler );
        findViewById(R.id.btnDiv).setOnClickListener( clickHandler );
        findViewById(R.id.btnRem).setOnClickListener( clickHandler );
    }

    private View.OnClickListener clickHandler = new View.OnClickListener (){
        public void onClick(View btnClicked) {
            // Get a reference to the etFN EditText of Layout
            EditText etFN = (EditText) findViewById(R.id.etFN);

            // Get a reference to the etSN EditText of Layout
            EditText etSN = (EditText) findViewById(R.id.etSN);

            // Get a reference to the tvResult TextView of Layout
            TextView tvResult = (TextView) findViewById(R.id.tvResult);

            // Type Cast etFN and etSN Text into String and then into Value
            double fn = Double.parseDouble(etFN.getText().toString());
            double sn = Double.parseDouble(etSN.getText().toString());

            switch (btnClicked.getId()) {
                case R.id.btnAdd:
                    // tvResult = etFN + etSN
                    tvResult.setText(String.valueOf(fn + sn));
                    break;

                case R.id.btnSub:
                    // tvResult = etFN - etSN
                    tvResult.setText(String.valueOf(fn - sn));
                    break;

                case R.id.btnMul:
                    // tvResult = etFN x etSN
                    tvResult.setText(String.valueOf(fn * sn));
                    break;

                case R.id.btnDiv:
                    // tvResult = etFN / etSN
                    tvResult.setText(String.valueOf(fn / sn));
                    break;

                case R.id.btnRem:
                    // tvResult = etFN % etSN
                    tvResult.setText(String.valueOf(fn % sn));
                    break;

                default:
            }
        }
    };
}

When we run the Android App with this Modified Event Handler Code, we still get the same output as was received by the Nested Event Listener Class created in the previous section. So we can specify our Event Handler using whichever method we want.

Read Also – What is Android Activity Life Cycle? Life Cycle Methods and Callbacks

About dmtechnolab

Check Also

Simplified Coding

Android Espresso Tutorial – Testing Fragment in Isolation – Android Coding by DMTechnolab

Welcome to another tutorial in the Android test series. And this post is called Android …

5 comments

  1. One thing I would really like to say is that often before purchasing more pc memory, check out the machine into which it is installed. When the machine is actually running Windows XP, for instance, the particular memory ceiling is 3.25GB. Using over this would just constitute any waste. Be sure that one’s motherboard can handle your upgrade volume, as well. Great blog post.

  2. Thanks for your write-up on the vacation industry. I might also like to add that if you are one senior thinking of traveling, its absolutely crucial that you buy traveling insurance for elderly people. When traveling, older persons are at high risk of experiencing a medical emergency. Obtaining the right insurance package for one’s age group can safeguard your health and provide you with peace of mind.

  3. At this time I am going to do my breakfast, once having my breakfast coming again to
    read additional news.

  4. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 certain. Any tips or advice would be greatly appreciated. Appreciate it

  5. Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t show up.
    Grrrr… well I’m not writing all that over again. Anyhow, just wanted to
    say wonderful blog!

Leave a Reply

Your email address will not be published. Required fields are marked *