,所以我希望通過創建一個名爲SearchableModel
抽象類,它看起來像這是聰明的:使用抽象類作爲RecyclerView適配器的基礎?
public abstract class SearchableModel {
public abstract String getId();
public abstract String getName();
}
,然後創建一個RecyclerViewAdapter會延長這一抽象的任何一類的工作。我的具體類看起來是這樣的:
public class School extends SearchableModel{
@SerializedName("external_school_id")
private String id;
@SerializedName("name")
private String name;
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return id;
}
}
而且RecyclerViewAdapter是這樣的:
public class SearchableItemAdapter extends RecyclerView.Adapter<SearchableItemAdapter.ViewHolder> {
private List<SearchableModel> items;
public SearchableItemAdapter(List<SearchableModel> items) {
this.items = items;
}
@Override
public SearchableItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(SearchableItemAdapter.ViewHolder holder, int position) {
SearchableModel item = items.get(position);
holder.nameText.setText(item.getName());
}
@Override
public int getItemCount() {
return items.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.text_list_name)
TextView nameText;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
我的想法是,我只想能夠定義一個List<School> schools
,然後將其應用到該適配器構造函數使用new SearchableItemAdapter(schools)
。然而,當我嘗試這個,我得到以下錯誤:
Incompatible Types. Required List<SearchableModel>. Found List<School>
我的理解是,因爲學校延伸SearchableModel它應該能夠代替它被使用。我完全脫離Java中的繼承方式,還是有其他事情在這裏發生?
我只是想通了這一點,你的回答。謝謝! – drawinfinity