java - 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());
如果您需要更多详细信息,请告诉我,谢谢
解决方案
我不是安卓开发者,所以不能给你一个真实的例子。让我们定义接口如下(我不知道你需要的真正方法,所以只是做了一个简单的例子)
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
推荐阅读
- javascript - Javascript 规范说什么应该从 NodeList 上的越界数组索引返回
- c# - 在对象列表上实现 INotifyPropertyChanged?
- eclipse-collections - 使用 Eclipse Collections 库,如何根据值对 MutableMap 进行排序?
- json - 如何使用 jq 将数据从一个 json 复制到另一个
- php - 得到错误的数组php sql
- python - 为什么禁用 2captcha 的提交按钮?
- javascript - 状态更改后未调用 React\Redux 渲染()
- html - 如何使用 css 对文本进行排序?
- mysql - SUM OVER PARTITION BY 2 最后一行相同的值
- html - 当打印太长的文本时,角度会覆盖文本而不是下一行