This article mainly introduces the relevant information about the detailed explanation of java interface callback examples. The so-called callback is the use of polymorphism in java. Friends in need can refer to it
java interface callback examples detailed explanation
First of all, the official definition of interface callback is as follows. The so-called callback: It means that class A calls a method C in class B, and then class B in turn calls methods D and D in class A. This method is called the callback method. This sounds a bit convoluted, but we can understand interface callbacks this way: For example, we want to know when Mr. Wang next door will come home? But we have our own things to do and cannot keep an eye on Lao Wang all the time, so we can hire security guards from the community to complete this task. When Lao Wang comes home, the security guard calls us to tell us that Lao Wang is back! This completes the delivery of an event;
First we define an interface:
public interface DynamicMessageListener { /** * 获取网络数据, * @param bean bean 对象 */ void getDynamicData(List<DynamicBean.DataBean> bean, boolean isMore); }
Define a class to implement this interface:
public class DynamicFragment extends Fragment implements DynamicMessageListener { //初始化监听者 private DynamicMessageListener listener; /** * 获取网络数据 * * @param bean bean 对象 */ @Override public void getDynamicData(List<DynamicBean.DataBean> bean, boolean isMore) { if (bean != null && bean.size() > 0) { if (!isMore) { adapter = new DynamicAdapter(mContext, bean, this, classID); friendLv.setAdapter(adapter); adapter.setListener(this); LLog.e("activity------有数据"); } else { adapter.setData(bean); } } } }
Call the above method at the network request layer:
public class DynamicModel extends BaseModel { private Context mContext; private NetUtils net; private DynamicMessageListener listener; public DynamicModel(Context mContext, DynamicMessageListener listener) { this.mContext = mContext; net = NetUtils.getInstance(); this.listener = listener; } /** * 加载网络数据, * @param url 网络url * @param params 请求网络携带的参数 */ public void loadData(String url, RequestParams params) { net.sendGetRequest(url, params, new NetUtils.NetUtilsCallBack() { @Override public void getNetdata(String json) { if (json != null) { Gson gson = new Gson(); DynamicBean bean = gson.fromJson(json, DynamicBean.class); List<DynamicBean.DataBean> data = bean.getData(); listener.getDynamicData(data, false); if(data ==null||data.size() <=0 ){ listener.friendsNoData(false); LLog.e("没有数据-----"); } } } @Override public void loadError(int a) { showError(a, mContext); } }); } }
The above is the detailed content of Example code sharing about interface callbacks in Java. For more information, please follow other related articles on the PHP Chinese website!