从Tablayout Fragment(Android)

时间:2018-04-15 13:02:47

标签: java android interface fragment android-tablayout

我不确定这是完美的标题,但它是我能想到的最好的。

我有一个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

但这适用于常规活动,所以它真的让我处于优势地位。对此的修复将非常感激。对我来说,这是一个受教育的时刻。谢谢

1 个答案:

答案 0 :(得分:1)

要构建ApiRequest对象,您将传递上下文。在构造函数中,您假设您始终可以将此上下文强制转换为ApiRequestCallback(这是您正在执行的错误)。就像在你的片段中一样 - 片段没有自己的上下文,当你在片段中使用getContext()时,它返回父活动的上下文,这在你的ApiRequest类的构造函数中不能转换为ApiRequestCallback。

将ApiRequest构造函数更改为:

public ApiRequest (Context context, ApiRequestCallback api_request_callback){
       this.context = context;
       this.api_request_callback = api_request_callback;
}

然后在你的片段中使用:

api_request = new ApiRequest(getContext(), Home .this);