Interface callback in Android practice

Source: Internet
Author: User

Interface callback in Android practice

As I used to be stuck in abstract, interface, and other "scary" things, and lack of practical explanations on the internet, I am afraid to share my understanding with you.

I am also self-taught and "talented". I am not interested in software development even though I learned computers in college. After graduation, I quickly found a good job after watching my classmates or training Android or IOS for 4 months, which surprised me and envied me! So I made an important decision in my life and started to learn Android. Because I was poor, I chose to learn Android by myself. The process of learning is really not easy. From the first time I knew nothing about it, I had to struggle, and I had to learn how to deal with it.

Java learners should know the three main characteristics of object-oriented: encapsulation, inheritance, and polymorphism. 2/3 of them involve abstraction (Inheritance and polymorphism), so we can see the importance of abstraction. The word abstraction sounds very abstract, and it is also very abstract. The interface is a special abstract class (the methods in the class are all abstract methods), which is more abstract. I have always known the existence of abstraction, but I have never known how to use it or how to ask others. So I wrote the code to do the project until one time. Someone has to ask, isn't it possible to write projects without using abstraction, interfaces, and other things? What I want to talk about is that the quality of the Code is different. Otherwise, why do brick companies need to invent it ?!

During the project, I once discussed some issues with my server colleagues. He looked at my code and found a serious problem, that is, requesting network operations. I reference AsyncHttpClient. jar. Every network request:

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, Header [] headers, byte [] responseBody, Throwable error ){}
}

 

Therefore, new AsyncHttpClient () is required in a live Fragment of an Activity. Many times, this will also produce a lot of repetitive code, which is not clear and does not conform to the single responsibility principle. So he helped me to separate the network request operation into a class so that it could be reused. The interface is used to reconcile Fragment or Activity interaction. I felt so good that I had a clear understanding of the interface:

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, The result parsed asynchronously from the network is passed to the subclass. requestUrl is a flag to determine which request it is. Subclass implements 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 I wrote, code: http://download.csdn.net/detail/gaolei1201/8936209

 

The interface callback condition is an interface. Two Classes operate on each other. It complies with the Dependency inversion principle of the six principles of JAVA design patterns. For the six principles of the design model, refer to my previous blog: http://blog.csdn.net/gaolei1201/article/details/47082783. For more information about the interface callback, see: http://www.bkjia.com/kf/201412/365788.html

 

The following example shows that Fragment is a common component in projects, but how do you implement interaction between them? It is difficult for others to do it, as I did before. For example, if FragmentA wants to change the FragmentB UI, you may first want to write a method such as changeFragmentUI () in FragmentB to change the FragmentB UI, 1. The first thing you think of is new FragmentB (). changeFragmentUI (), but after you try it, it is not possible to report: NullPointerException. This is because you have a new FragmentB, and the component to be changed is initialized in the original FragmentB. 2. Set changeFragmentUI to static, then FragmentB. chaneFragmentUI () can be used (). In this way, although no NULL pointer exception is reported, all the variables in the static method must be static, that is, the components you want to change the UI must be declared as static, if there is too much static, it is definitely not good. If the interface callback is used, all your troubles will be solved. The following is an example of how to implement interaction between two Fragment to change the UI of each other. Of course you can also use the official Fragment communication method: http://blog.csdn.net/gaolei1201/article/details/47045461

The LeftFragment code is as follows:

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); in this case, the set cannot be used, because it creates a new RightFragment, which is not the same as the one originally initialized, and returns a null pointer, because the listener of RightFragment is not set (instantiated ). So it should be like this RightFragment. setOnFragmentChangeListener (this );*/
RightFragment. setOnFragmentChangeListener (this );

Change_activity_bt.setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View arg0 ){
// TODO Auto-generated method stub
// Execute the interface method here
OnFragmentChangeListener. onFragmentChange ();
}
});
Return view;
}
@ Override
Public void onFragmentChange (){
// Method for implementing the interface in the subclass
Show_change_text.setText (I am LeftFragment, and I have changed );
}
}

 

The following is the RightFragment code, which is almost the same as LeftFrgment because they have the same 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); in this case, the set cannot be used, because it creates a new LeftFragment, which is not the same as the one originally initialized, and returns a null pointer, because the listener of LeftFragment is not set (instantiated ). So LeftFragment. setOnFragmentChangeListener (this );*/

LeftFragment. setOnFragmentChangeListener (this );

Change_activity_bt.setOnClickListener (new OnClickListener (){

@ Override
Public void onClick (View arg0 ){
// TODO Auto-generated method stub
// Execute the interface method here
OnFragmentChangeListener. onFragmentChange ();
}
});
Return view;
}
@ Override
Public void onFragmentChange (){
// Method for implementing the interface in the subclass
Show_change_text.setText (I am RightFragment, and I have changed );
}

 

 

 

This is not for Daniel. Abstract and interface are indeed abstract. This requires continuous learning and summarization. More importantly, you can use it in projects. Then, you will understand its role and discover its advantages, oh Yeah!

 

 

 

 

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.