Java 泛型从活动到片段再到适配器



我在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());

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

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

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

具有未知实现类的泛型工厂

最新更新