Interface callback technology in Android

Source: Internet
Author: User

The interface callback technology in Android has a lot of applications, the most common: the Activity (Human-computer interface) UI defines the button, when clicked on the button, the execution of a certain logic.

The following model, described above, describes James ' understanding of the Android Interface callback technology (in combination with previous knowledge and his own practice).

The use of a metaphor is very vividly illustrated: the client has a question to call the server, but the service can not be answered on the spot, the agreement between each other: the service side once the answer, the use of telephone feedback to the client.

There are three principals: client, server, and interface (mode).

The schematic diagram of the interface callback illustrates:

The demo interface is as follows:

The actual results are as follows:

Where Todolistactivity's layout XML file is designed to be populated with fragment tags.

<LinearLayoutxmlns: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"android:orientation= "vertical"Tools:context= "Com.demo.ToDoListActivity" >    <FragmentAndroid:id= "@+id/fragment_new_item"Android:name= "Com.demo.NewItemFragment"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" />    <FragmentAndroid:id= "@+id/fragment_todo_list"Android:name= "Com.demo.ToDoListFragment"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content" /></LinearLayout>

Demo Source code:

 PackageCom.demo;Importandroid.app.Activity;Importandroid.app.Fragment;ImportAndroid.os.Bundle;Importandroid.text.TextUtils;Importandroid.view.KeyEvent;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.View.OnKeyListener;ImportAndroid.view.ViewGroup;ImportAndroid.widget.EditText;/*** < function description > fragment defined for new item * *@authorAdministrator*/ Public classNewitemfragmentextendsFragment {Private Static FinalString TAG = newitemfragment.class. Getsimplename (); /*** < function description > Step 1: Create the specified interface * *@authorAdministrator*/     Public InterfaceOnnewitemaddedlistener {//Step 2: Create a related method in the interface         Public voidonnewitemadded (String newitem); }
//Step 3: Declare the callback interface object, interface class object PrivateOnnewitemaddedlistener Onnewitemaddedlistener;
@Override Public voidOnattach (activity activity) {Super. Onattach (activity); Try { //Step 4: Get the parent activity, assign a value to the declared interface objectOnnewitemaddedlistener =(Onnewitemaddedlistener) getactivity (); } Catch(Exception e) {Throw Newclasscastexception (activity.tostring ()+ "must implement Onnewitemaddedlistener"); } }
@Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {//Create or populate the Fragment UI and return to the View objectView Contentview =inflater.inflate (r.layout.new_item_fragment, container,false); FinalEditText etcontent =(EditText) contentview. Findviewbyid (r.id.et_content); Etcontent.setonkeylistener (NewOnkeylistener () {@Override Public BooleanOnKey (View V,intKeyCode, KeyEvent event) { if(event.getaction () = =Keyevent.action_down) {LOGUTIL.D (TAG,"Keyevent.action_down"); if(KeyCode = =keyevent.keycode_dpad_center)|| (KeyCode = =keyevent.keycode_enter)) {LOGUTIL.D (TAG,"Keyevent.keycode_enter"); if(!Textutils.isempty (Etcontent.gettext (). toString ())) {LOGUTIL.D (TAG,"Content:>" + etcontent.gettext (). toString () + "<"); String content=Etcontent.gettext (). toString (); //Step 5: Create a scenario that uses the interface callback methodonnewitemaddedlistener.onnewitemadded (content); Etcontent.settext (""); return true; } } } return false; } }); returnContentview; }}

Activity source code for user and interface UI interaction:

 PackageCom.demo;Importandroid.app.Activity;ImportAndroid.app.FragmentManager;ImportAndroid.os.Bundle;ImportAndroid.widget.ArrayAdapter;ImportCom.demo.NewItemFragment.OnNewItemAddedListener;Importjava.util.ArrayList;/*** < function description > Step 6: Use in other classes and implement the interface * *@authorAdministrator*/ Public classTodolistactivityextendsActivityImplementsOnnewitemaddedlistener {Private Static FinalString TAG = todolistactivity.class. Getsimplename (); PrivateArraylist<string>Mtodoitem; PrivateArrayadapter<string>Marrayadapter;
@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Initview (); InitData (); //Gets the Fragmentmanager instance that gets the fragment in the XML fileFragmentmanager Fragmentmanager =Getfragmentmanager (); Todolistfragment todolistfragment=(todolistfragment) fragmentmanager. Findfragmentbyid (r.id.fragment_todo_list); Todolistfragment.setlistadapter (Marrayadapter); } Private voidInitview () {Setcontentview (r.layout.main); } Private voidInitData () {Mtodoitem=NewArraylist<string>(); Marrayadapter=NewArrayadapter<string> ( This, Android. R.layout.simple_list_item_1, Mtodoitem); } @Overrideprotected voidOnresume () {Super. Onresume (); LOGUTIL.D (TAG,"Onresume ..."); } @Override Public voidonnewitemadded (String newitem) {//Step 7: Implement the interface and use the features in itMtodoitem.add (0, NewItem); Marrayadapter.notifydatasetchanged (); }}

The todolistactivity of the demo above implements the interface Onnewitemaddedlistener in the custom newitemfragment, and it is necessary to implement the abstract method in the interface. Through the following methods:

// Step 4: Get the parent activity, assign a value to the declared interface object Onnewitemaddedlistener = (onnewitemaddedlistener) getactivity ();

The todolistactivity instance is passed to Newitemfragment, which is the ability to execute the onnewitemadded () method in the Todolistactivity instance. And this method is covered by the todolistactivity (the actual implementation is the method and logic after the overwrite).

Overview of the interface callback technology in Android:

The Android interface callback method requires a total of 7 steps to be performed:

1. Create the specified interface class and create the relevant method in the interface;

2. Declare an interface object (creating the Interface class object) in a class (typically a server), that is, the interface needs to be used in that class;

3. Assign a value to the interface class object (that is, the server typically instantiates the interface object, using the client's interface instance initialization) in the scenario where the interface object is used (typically the server side);

5. The method in the interface callback (the method of the interface) is used in this scenario (the General Service side);

6. The assignment object in step 4 above (the client passes the instance object, there are many methods: the new interface instance or the client implements the interface) needs to implement the interface;

7. The class (client) in step 6 above, overwrite the method in the interface;

Interface callback technology in Android

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.