java - 从 Tablayout Fragment ( Android) 实现接口(interface)

标签 java android interface fragment android-tablayout

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

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

相关文章:

java - 简单测试中的 NoClassDefFoundError

java - 为什么 ArrayList 有 "implements List"?

java - 在 junit 测试中模拟用户控制台输入

android - 在 Android 注释中继承

android - 在 android 11(sdk 30) 中,如何从下载文件夹上传 pdf 文件?我收到权限被拒绝的 EACCES 消息

android - 键盘一直挡住我的视线...如何解决?

java - 如何将所有依赖的 Jar 包含在一个不可执行的 jar 中?

android - 如何在 Android 中的 ACTION_CALL 之后返回到我的应用程序

java - 如何在接口(interface)类型的引用上调用 Object 类的方法?

C# 父子接口(interface)