【发布时间】:2018-04-15 13:02:47
【问题描述】:
我不确定这是不是完美的标题,但它是我能想到的最好的标题。
我有一个 java 类 ApiRequest 运行一些 http 请求并通过接口在回调中返回结果。示例将是下面的身份验证方法:
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 );
}
现在我在 tablayout 中有一个片段类,它在下面实现了这个类
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
}
}
我得到的响应是我不能强制转换:活动上下文到界面。
Java.lang.ClassCastException: com.*****.**** cannot be cast to com.*****.****ApiRequest$ApiRequestCallback
但这适用于常规活动,所以它真的让我处于边缘。对此的修复将不胜感激。我会说,这是一个可教的时刻。谢谢
【问题讨论】:
标签: java android interface fragment android-tablayout