Android Combat Universal Interface Callback

Source: Internet
Author: User

Reprint please indicate the original address: http://blog.csdn.net/gaolei1201/article/details/47084111


Foreword: I am also self-taught "talent", hehe, although the University of computer, but not interested in software development.

After graduating to see the students or training Android or training iOS 4 months after the very fast found a good job. I am very surprised, but also very envious! So I made an important decision in my life. Start learning Android. Because I am poorer, so I choose to teach myself.

The process of learning is not easy, from the beginning of the unknown when the struggle, to learn to have a strategy after the response, all rely on their own diligence good ask.

Because I have been trapped in the abstract, interface and other "scary" things, the lack of on-line in the project in the actual use of the commentary, the following I would venture to their understanding and everyone to exchange next.


People who learn Java should all know the three main features of object-oriented: encapsulation, inheritance, polymorphism. Almost all involved interfaces and abstractions. And the six principles of Java design Patterns almost all involve interfaces and abstractions. Thus , the importance of abstraction can be seen. Abstract this word sounds very abstract, learning is very abstract, and interface is a special abstract class (the method inside the class is all abstract method). That's more abstract.

I have always known the existence of abstraction, but have never known how to use it and what its advantages. I don't know how to ask someone.

So I wrote the code to do the project until once.

Someone has to ask, do not use abstract, interface and other things can not write projects? I would like to say that the quality of the code is different, or why the brick family to invent it?!


In the process of doing the project, there was one time to discuss some issues with the server colleagues. He looked at my code and found a more serious problem, which was to request a network operation. I am referring to Asynchttpclient.jar, each time the network request is:

Requestparams params = new Requestparams (); new Asynchttpclient (). Post (Requesturl, Params,new Asynchttpresponsehandler () {public void onsuccess (int statusCode, header[] headers,byte[] responsebody) {}public void onfailure (int statusCode, He Ader[] headers,byte[] responsebody, throwable error) {}}

So in an activity fragment to new Asynchttpclient (), many times. This will also produce a lot of repetitive code, and unclear, not in line with the principle of single responsibility. So he helped me get the network request operation out of a class, so that it could be reused. The interface callback is then interacted with fragment or activity. I feel so good, my understanding of the interface is also enlightened:

Public  class Netrequest  {private Netrequestiterface netrequestiterface;private Context context;public Netrequest (netrequestiterface netrequestiterface,context Context) {this.netrequestiterface= NetRequestIterface; This.context=context;}        Requestparams params = new Requestparams (), if (Null!=map&&!map.isempty ()) for (String Key:map.keySet ()) {params . put (Key, Map.get (key));}      New Asynchttpclient (). Post (Requesturl, Params,new Asynchttpresponsehandler () {public     void onsuccess (int StatusCode, header[] headers,byte[] responsebody) {     //here is the result of the asynchronous parsing of the network passed to the subclass, Requesturl is a flag that infers which request. Subclasses implement ChangeView ()      Netrequestiterface.changeview (result, Requesturl);   }    public void onfailure (int statusCode, header[] headers,byte[] responsebody, throwable error) {}   

This is a small demo of a network operation interface callback that I wrote, the code:

http://download.csdn.net/detail/gaolei1201/8936209


The condition of an interface callback is an interface. Two classes, two classes to manipulate each other. Regardless of the two classes, such as service and activity,fragment and fragment. Fragment and activity and so on. It conforms to the six principles of Java design Pattern dependency inversion principle.

The six principles of design patterns can be tested in my previous blog: http://blog.csdn.net/gaolei1201/article/details/47082783.

Here is a more illustrative example. Fragment are frequently used components in a project, but how do they interact with each other? It is more difficult for a person not to be brought up to do it. Like I used to be. If Fragmenta wants to change Fragmentb's UI, you might first think of writing a method like Changefragmentui () in FRAGMENTB to change Fragmentb ui,1, the first thing you think about is new FRAGMENTB (). Changefragmentui (), but you try to find it is not good newspaper: NullPointerException. This is because you have another new FRAGMENTB. The component that needs to be changed is initialized in the original FRAGMENTB.

2, the Changefragmentui is set to static, then you can Fragmentb.chanefragmentui ().

This way, although the null pointer exception is not reported, the variables inside the static method must all be static. The component that you want to change the UI to declare is static. Think about it. It is certainly not good to assume that there is too much static.

This assumes that the interface callback will solve all your problems, and the following example implements the interaction between two fragment to change a sample of each other's UI.

Of course you can also use the official fragment to communicate between the methods: http://blog.csdn.net/gaolei1201/article/details/47045461

For example, the following leftfragment code:

public class Leftfragment extends Fragment implements Onfragmentchangelistener {private TextView show_change_text; Private Button change_activity_bt;public static onfragmentchangelistener onfragmentchangelistener;public static void Setonfragmentchangelistener (Onfragmentchangelistener onfragmentchangelistener) { Rightfragment.onfragmentchangelistener=onfragmentchangelistener;} Public View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {Super.onCreateView ( Inflater, container, savedinstancestate); View view = Inflater.inflate (r.layout.right_fragment, null); CHANGE_ACTIVITY_BT = (Button) View.findviewbyid ( R.ID.CHANGE_ACTIVITY_BT); show_change_text = (TextView) View.findviewbyid (r.id.show_change_text);/* NEW Rightfragment (). Setonfragmentchangelistener (this); This set is not possible, because this again creates a rightfragment, and the original initialization of the one is not a, will be reported null pointer, because Rightfragment's listener is not set (instantiation). So it should be rightfragment.setonfragmentchangelistener (this); */rightfragment.setonfragmentchangelistener (this); ChangE_activity_bt.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO Auto-generated method stub//Here runs the interface methods Onfragmentchangelistener.onfragmentchange ();}); return view;} @Overridepublic void Onfragmentchange () {//method for implementing interfaces in subclasses Show_change_text.settext ("I am leftfragment,and I have changed") ;}} For example, the following is the Rightfragment code, and Leftfrgment almost as well, because of their logic: public class Rightfragment extends Fragment implements Onfragmentchangelistener {private TextView show_change_text;private Button change_activity_bt;public Static Onfragmentchangelistener onfragmentchangelistener;public static void Setonfragmentchangelistener ( Onfragmentchangelistener onfragmentchangelistener) {rightfragment.onfragmentchangelistener= Onfragmentchangelistener;} Public View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {Super.onCreateView ( Inflater, container, savedinstancestate); View view = Inflater.inflate (r.layout.right_fragment, null); CHANGE_ACTIVITY_BT = (Button) VIEw.findviewbyid (R.ID.CHANGE_ACTIVITY_BT); show_change_text = (TextView) View.findviewbyid (R.id.show_change_text); * New Leftfragment (). Setonfragmentchangelistener (this); This set is not possible. Since this creates a leftfragment again, it is not one of the original initialized. A null pointer is reported. Since Leftfragment's listener is not set (instantiated). So Leftfragment.setonfragmentchangelistener (this), */leftfragment.setonfragmentchangelistener (this); Change_ Activity_bt.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method stub//here runs the interface methods Onfragmentchangelistener.onfragmentchange ();}); return view;} @Overridepublic void Onfragmentchange () {//method of implementing an interface in a subclass Show_change_text.settext ("I am rightfragment,and I have changed" );}

Some specific information about interface callbacks can be tested:

1. clarify the Android interface callback mechanism:http://www.2cto.com/kf/201412/365788.html

2. Callback in Android : http://blog.csdn.net/lindir/article/details/7819720

3. A classic example that gives you a thorough understanding of the Java callback mechanism :http://blog.csdn.net/xiaanming/article/details/8703708/


That's not what Daniel said. Abstract, interface is indeed more abstract this need to learn, summarize, more importantly, in the project to apply it. After that, you will understand its role, find its strengths, a return to two cooked three back you become a master, Come on baby! Oh yeah!


this is demo:http://download.csdn.net/detail/gaolei1201/8936215 .






Android Combat Universal Interface Callback

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.