首页 > 解决方案 > Java Generic 从 Activity 到 Fragment 到 Adapter

问题描述

我在android应用程序中工作,设计了一个通用适配器,参数化适配器将继承它。

public abstract class CarAdapter<T> extends RecyclerView.Adapter<CarAdapter<T>.BaseCarViewHolder> {
    protected DialogMakerCar<T> dialogMaker;
    protected Context context;
......

儿童班

public class CarItemAdapter extends CarDialogAdapter<Item> {

    public CarItemAdapter(Context context, DialogMakerCar<Item> dialogMaker) {
        super(dialogMaker, context);
    }

我在片段中调用此适配器,并且该片段也需要是通用的,以便我可以为来自活动的自定义对象调用此片段和适配器。

//Fragment to call adapter but its not letting me to use <T> generic 
 adapter = new CarItemAdapter(getContext(),dialogMaker);
        gridRecycler.setHasFixedSize(true);
        gridRecycler.setLayoutManager(adapter.getLayoutManager());

如果您需要更多详细信息,请告诉我,谢谢

标签: javaandroidandroid-fragmentsgenerics

解决方案


我不是安卓开发者,所以不能给你一个真实的例子。让我们定义接口如下(我不知道你需要的真正方法,所以只是做了一个简单的例子)

public interface ICarAdapter {

    public <T> DialogMakerCar<T> getDialogMaker();

    public Context getContext();

}

您可以定义 T 扩展的内容以避免在其他类中使用时出现警告。

现在你需要在你定义的类中使用这个接口:

public class CarItemAdapter extends DialogMakerCar<Item> implements ICarAdapter{
  private DialogMakerCar<Item> dialogMakerCar;
  private Context context;

  public CarItemAdapter(Context cntxt, DialogMakerCar<Item> dialogMaker) {
    dialogMakerCar = dialogMaker;
    context = cntxt;
  }

  /** This will give you a warning, can be avoided 
      if you define in the interface that T extendes 
      an interface that Item implements.*/
  @Override
  public DialogMakerCar<Item> getDialogMaker() {
    return dialogMakerCar;
  }

  @Override
  public Context getContext() {
    return context;
  }
}

在片段类中:

public class Fragment {
   
  public <T> ICarAdapter createAdapter(T item) {
    //You can manage this as you want, 
    //with a switch, defining an Enum or passing the Class that you want. 
    if (item instanceof Item) {
        return new CarItemAdapter(getContext(),dialogMaker);
    }
    return null;
}

然后当你想使用它时:

public class Activity {

    Fragment fragment;

    ICarAdapter adapter;

    public Activity() {
        fragment = new Fragment();
        Item item = new Item();
        adapter = fragment.createAdapter(item);
        adapter.getContext();
        adapter.getDialogMaker();
    }

希望至少它可以帮助你一点。

执行此操作的其他方法:

https://dzone.com/articles/java-generic-factory

https://stackoverflow.com/a/47464801/6708879

具有未知实现类的通用工厂


推荐阅读