如何使用相同的回收适配器给不同的布局充气?



我正在使用wordAdapter类来回收列表视图,我想在给定条件下膨胀不同的布局,例如如果标志等于1而不是膨胀activity_all布局,如果标志等于2而不是膨胀activity_food布局,但是当我尝试使用以下代码时,我的应用程序崩溃了

CountingActivity countingActivity;
FoodActivity foodActivity;
//Making constructor of the class wordAdapter which takes Activity and ArrayList as arguments
public wordAdapter(Activity context, ArrayList<word> words,int flag){
super(context,0,words);
}
@NonNull
public View getView(int position,@NonNull View convertView,@NonNull ViewGroup parent){
View listItemView = convertView;
//Checking if recycle view is available or not
if(listItemView == null)
{
if (countingActivity.flag == 1) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.activity_all,parent,false);
}
else if(foodActivity.flag == 2)
{
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.activity_food,parent,false);
}
}

您可以在onCreateViewHolder部分添加它

@NonNull
@Override
public YouAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == 0)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_one, parent, false);
return new v;
}else
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_xml_two, parent, false);
return new v;
}
}

在你的适配器类中,你需要在顶部声明类型,比如

private static final int VIEW_ITEM = 1;
private static final int LOADING = 0;
private static final int VIEW_TYPE_EMPTY = 2;

onCreateViewHolder中,您需要像这样声明视图持有者

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder vh = null;
switch (viewType) {
case VIEW_TYPE_EMPTY:
View emptyView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_view_no_data, parent, false);
vh = new EmptyViewHolder(emptyView);
break;
case VIEW_ITEM:
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_view_game_details, parent, false);
vh = new GameViewHolder(itemView);
break;
case LOADING:
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_progress_bar, parent, false);
vh = new ProgressViewHolder(v);
break;
}
return vh;
}

onBindViewHolder中,您需要首先根据实例检查viewholder的实例和类型转换

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof GameViewHolder) {
/** You code for you ViewHlder**/
} else if (holder instanceof ProgressViewHolder) {
/** You code for you ViewHlder
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
**/
}
}

最新更新