【问题标题】:Implementing interface from Tablayout Fragment ( Android)从 Tablayout Fragment 实现接口(Android)
【发布时间】: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


    【解决方案1】:

    要构造您的 ApiRequest 对象,您需要传递上下文。在构造函数中,您假设您始终可以将此上下文强制转换为 ApiRequestCallback (这是您正在做的错误)。就像在您的片段中一样 - 片段没有自己的上下文,当您在片段中使用 getContext() 时,它会返回父活动的上下文,并且您的 ApiRequest 类的构造函数中的 this 不能转换为 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);
    

    【讨论】:

    • 谢谢,但为什么我要在 ApiRequest 中将 apiRequestCallbask 作为参数传递?
    • 因为您需要它在您的 ApiRequest 类中初始化 api_request_callback。它适用于活动,因为它有自己的上下文。但是对于所有其他的东西,比如你的适配器或片段,它们没有自己的上下文。所以 context 和 ApiRequestCallback 接口不能是同一个对象。所以你需要发送参数。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多