android 回调怎么写
时间: 2024-01-01 13:04:53 浏览: 27
在 Android 中,回调通常是通过接口(Interface)实现的。
首先,定义一个接口,例如:
```
public interface OnDataReceivedListener {
void onDataReceived(String data);
}
```
接着,在需要使用回调的类中,定义一个接口类型的成员变量和一个设置回调的方法,例如:
```
public class DataFetcher {
private OnDataReceivedListener onDataReceivedListener;
public void setOnDataReceivedListener(OnDataReceivedListener listener) {
this.onDataReceivedListener = listener;
}
public void fetchData() {
// 获取数据的代码
String data = "这是获取到的数据";
// 调用回调方法
if (onDataReceivedListener != null) {
onDataReceivedListener.onDataReceived(data);
}
}
}
```
最后,在使用 DataFetcher 类的地方,实现 OnDataReceivedListener 接口并设置回调即可:
```
DataFetcher dataFetcher = new DataFetcher();
dataFetcher.setOnDataReceivedListener(new OnDataReceivedListener() {
@Override
public void onDataReceived(String data) {
// 处理获取到的数据
}
});
dataFetcher.fetchData();
```
这样,当 fetchData 方法获取到数据后,就会调用 onDataReceivedListener.onDataReceived 方法,从而触发回调。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)