我有3個不同的ArrayList
s和每個具有來自特定對象的數據:Type_A
,Type_B
和Type_C
。每個人都有一個字段private String name
,所以我將該字段移至Type_General
,並將所有3種類型擴展爲一般類型。創建通用類型適配器類不工作
我想用一個適配器項目的每個列表,我想,如果他們都繼承同一類型(Type_General
)和適配器使用List<Type_General>
我不會要創建3個不同的適配器,一個用於所有類型。
但要因爲它需要一個List<Type_General>
,我通過我的Adapter類的List<Type_A>
代碼我遊時,我試圖實例化一個Type_A
我在我的IDE(Android Studio
)有一個紅線錯誤:
class SuggestionsAdapter extends RecyclerView.Adapter<SuggestionsAdapter.ViewHolder> {
private List<Type_General> mDataset;
private EditProfileFragment.SuggestionsEditTextEnum editTextEnum;
private EditText editText;
private RecyclerView recyclerView;
class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
ViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
SuggestionsAdapter(List<Type_General> myDataset, EditProfileFragment.SuggestionsEditTextEnum editTextEnum,
EditText editText, RecyclerView recyclerView) {
mDataset = myDataset;
this.editTextEnum = editTextEnum;
this.editText = editText;
this.recyclerView = recyclerView;
}
@Override
public SuggestionsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.textview_with_rounded_corners, parent, false);
return new ViewHolder((TextView) v);
}
@Override
public void onBindViewHolder(final SuggestionsAdapter.ViewHolder holder, final int position) {
holder.mTextView.setText(capitalizeFirstLetter(mDataset.get(position).getName()));
holder.mTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (editTextEnum) {
case Type_A:
recyclerView.setVisibility(View.GONE);
break;
case Type_B:
recyclerView.setVisibility(View.GONE);
break;
case Type_C:
recyclerView.setVisibility(View.GONE);
break;
}
}
});
}
public void addItem(Type_General item) {
mDataset.add(item);
}
public void addAllItems(List<Type_General> items) {
mDataset.clear();
mDataset.addAll(items);
}
@Override
public int getItemCount() {
return mDataset.size();
}
}
因爲Type_General
是Type_A
,Type_B
和Type_C
的父類,不應該這樣工作嗎?
收藏品不能鑄造到集合。但是你可以做'Collection collection =(Collection )((Object)yourParentClassCollection)',但這很醜陋。 –