Simple use of Interface (Interface) in Android

Source: Internet
Author: User
Tags mul

In Android interface (Interface)The simple use

the interfaces in Java can be considered as 只包含常量和抽象方法的抽象类 .

You can define an interface using the following methods:

 Public Interface Interfacedemo {    int i = ten;     void method1 ();     int method2 ();}

Use 1: Resolve "multiple inheritance" issues

The Java language itself does not support multiple inheritance of classes (multiple inheritance refers to a class that inherits from multiple classes, that is, a class has more than one superclass), but one class can implement multiple interfaces. In this way, we can define some abstract methods in the interface, indirectly to achieve the purpose of multiple inheritance.
For example:

    • MyInterface1.java
 Public Interface MyInterface1 {    void  fly ();}
    • MyInterface2.java
 Public Interface MyInterface2 {    void  Walk ();}
    • Bird.java
 Public class Implements MyInterface1, MyInterface2 {    privatestaticfinal String TAG = "Bird";    @Override    publicvoid  Fly () {        "I can Fly");    }    @Override    publicvoid  Walk () {        "I can Walk");}    }
Use 2: Define a Specification (protocol)

The same interface can have several different implementation classes, but each implementation class must override all of the abstract methods in the interface. That is, the interface does not consider how these implementation classes each implement these functions, but it requires that all implementation classes must have these capabilities.
For example:
First define the interface of a calculator: Calculator.java All classes that implement the interface must have the ability to calculate two numbers, subtract, multiply, divide.

 Public InterfaceCalculator {/**calculator can calculate two number of and*/    intAddintAintb); /**calculator can calculate the difference of two numbers*/    intSubintAintb); /**calculator can calculate the product of two numbers*/    LongMulintAintb); /**calculator can calculate two number of quotient*/    floatDivintAintb);}

Then define a class that implements the interface.ACalculator.java

 Public classAcalculatorImplementsCalculator {@Override Public intAddintAintb) {returnA +b; } @Override Public intSubintAintb) {returnAb; } @Override Public LongMulintAintb) {returnAb; } @Override Public floatDivintAintb) {return(float) A/(float) b; }}

Use Acalculator in other classes to calculate the sum of two numbers. Other classes do not need to know how the Acalculator is computed, only the relevant method definitions in the Calculator interface are needed.
Test.java

 Public class Test {    publicstaticvoid  main (string[] args) {        new acalculator ();         int sum = calculator.add (+);        System.out.println ("sum =" + sum);}    }
use 3: for callbacks

We know that in general the main thread is not to perform time-consuming tasks, if you encounter some time-consuming tasks (such as network requests, file read and write, database read and write, etc.), we will put it into the sub-thread to execute, when the execution is complete, the child thread will return the execution result to the main thread. This process is a callback.

See an example.
First, define a callback interface.
OnInfoFetchCallback.java

 Public Interface oninfofetchcallback {    /***      /void onsuccess (String info);     /***      /Void failure ();}

Define a task class for getting information, in which we perform some time-consuming operations.
InfoService.java

 Public classInfoservice {PrivateOninfofetchcallback callback;  PublicInfoservice (Oninfofetchcallback callback) { This. Callback =callback; }     Public voidGetInfo () {//simulate a time-consuming operationThread thread =NewThread (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (3000); //success of information acquisition, delivery of resultsCallback.onsuccess ("The result is:" +NewDate ()); } Catch(interruptedexception e) {//Information Acquisition failedcallback.failure ();        }            }        });    Thread.Start (); }}

The MainActivity method in the call in InfoService is performing a getInfo() time-consuming operation.

 Public classMainactivityextendsAppcompatactivityImplementsOninfofetchcallback {Private Static FinalString TAG = "Mainactivity"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }    /*** Get information *@paramView*/     Public voidfetchinfo (view view) {Infoservice service=NewInfoservice ( This);    Service.getinfo (); } @Override Public voidonsuccess (String info) {LOG.I (TAG, info); } @Override Public voidfailure () {log.i (TAG,"Failed to get information"); }}

Because the MainActivity interface is already implemented OnInfoFetchCallback , the object is instantiated InfoService and passed in directly this . When the task execution finishes, the call MainActivity onSuccess(String info) or failure() method returns the result.

MainActivityYou can also OnInfoFetchCallback use an anonymous inner class when you don't have to implement an interface.

As shown below:

  /*** Get information *@paramView*/     Public voidfetchinfo (view view) {Infoservice service=NewInfoservice (NewOninfofetchcallback () {@Override Public voidonsuccess (String info) {LOG.I (TAG, info); } @Override Public voidfailure () {log.i (TAG,"Failed to get information");        }        });    Service.getinfo (); }

The layout file is very simple and has only one button.

activity_main.xml

<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Cc.duduhuo.interfacedemo.MainActivity">    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Get Info"Android:onclick= "Fetchinfo"/></Relativelayout>

Three basic uses of the interface in Android have been introduced, the post-related code can be downloaded through the address below:

Related source Click here to download

Simple use of Interface (Interface) in Android

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.