我不确定这是一个完美的标题,但它是我能想到的最好的标题。
我有一个java类ApiRequest,它运行一些http请求并通过接口(interface)在回调中返回结果。示例如下验证方法:
public class ApiRequest {
private Context context;
private ApiRequestCallback api_request_callback;
public ApiRequest ( Context context ){
this.context = context;
// this can either be activity or context. Neither works in fragment
// but does in activity
this.api_request_callback = ( ApiRequestCallback ) context;
}
public interface ApiRequestCallback {
void onResponse(JSONObject response );
void onErrorResponse(JSONObject response );
}
public JsonObject authenticate(){
.... do stuff and when you get response from the server. This is some
kinda of async task usually takes a while
// after you get the response from the server send it to the callback
api_request_callback.onResponse( response );
}
现在我在选项卡布局中有一个 fragment 类,它实现了下面的此类
public class Home extends Fragment implements ApiRequest.ApiRequestCallback
{
// I have tried
@Override
public void onViewCreated(.........) {
api_request = new ApiRequest( getContext() );
}
// and this two
@Override
public void onAttach(Context context) {
super.onAttach(context);
api_request = new ApiRequest( context );
}
@Override
public void onResponse(JSONObject response) {
//I expect a response here
}
}
我得到的响应是我无法将: Activity 上下文转换为界面。
Java.lang.ClassCastException: com.*****.**** cannot be cast to com.*****.****ApiRequest$ApiRequestCallback
但这适用于常规 Activity ,所以它确实让我感到紧张。对此问题的修复将不胜感激。我想说,这对我来说是一个受教的时刻。谢谢
最佳答案
要构造 ApiRequest 对象,您需要传递上下文。在构造函数中,您假设您始终可以将此上下文强制转换为 ApiRequestCallback (这是您正在执行的错误)。就像在您的 fragment 中一样 - fragment 没有自己的上下文,当您在 fragment 中使用 getContext() 时,它会返回父 Activity 的上下文,并且 ApiRequest 类的构造函数中的 this 无法转换为 ApiRequestCallback。
将 ApiRequest 构造函数更改为以下内容:
public ApiRequest (Context context, ApiRequestCallback api_request_callback){
this.context = context;
this.api_request_callback = api_request_callback;
}
然后在你的 fragment 中使用这个:
api_request = new ApiRequest(getContext(), Home .this);
关于java - 从 Tablayout Fragment ( Android) 实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842228/