我有一个recyclerview.Adapter类这是我的班级: 当我在MovieViewHolder onCreateViewHolder类参数中传递int位置时不起作用:(
public class Main_Recycle_Adapter extends RecyclerView.Adapter<Main_Recycle_Adapter.MovieViewHolder> {
List<Main> movies = Collections.emptyList();
LayoutInflater layoutInflater;
Context context;
public Main_Recycle_Adapter(Context context, List<Main> movies){
this.context = context;
layoutInflater = LayoutInflater.from(context);
this.movies = movies;
}
//;;;;;;;;;;;;;;
@Override
public int getItemCount() {
return movies.size();
}
@Override
public long getItemId(int position) {
return position;
}
//[[[[[[[[[[[[[[[[[[
@Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType ) {
View row;
if ((position % 2) == 0 ){
row = layoutInflater.inflate(R.layout.grid_list3, parent, false);}
else{row = layoutInflater.inflate(R.layout.grid_list3, null);}
MovieViewHolder holder = new MovieViewHolder(row);
return holder;
}
@Override
public void onBindViewHolder(MovieViewHolder holder, int position) {
Main thisMovie = movies.get(position);
holder.tozih.setText(thisMovie.getName());
holder.tablooo.setImageResource(context.getResources().getIdentifier(thisMovie.getLogo(), "mipmap", context.getPackageName()));
}
public class MovieViewHolder extends RecyclerView.ViewHolder {
private TextView tozih;
private ImageView tablooo;
public MovieViewHolder(View itemView) {
super(itemView);
tozih = (TextView) itemView.findViewById(R.id.textView1);
tablooo = (ImageView) itemView.findViewById(R.id.imageView1);
}
}
}
这里我想要偶数和奇数行的位置:
if ((position % 2) == 0 ){
row = layoutInflater.inflate(R.layout.grid_list3, parent, false);}
else{row = layoutInflater.inflate(R.layout.grid_list3, null);}
但是位置仍然是红色,无法解决错误 在这种情况下我该怎么办? 提前谢谢
编辑感谢alex我已经完成了这件事:@Override
public int getItemViewType(int position )
{ int viewType ;
if((position % 2) == 0 )
viewType = 0;
else
viewType =1;
return viewType; }
//[[[[[[[[[[[[[[[[[[
@Override
public MovieViewHolder onCreateViewHolder(ViewGroup parent, int viewType )
{
View row;
if (viewType == 0 ){
row = layoutInflater.inflate(R.layout.grid_list2, parent, false);}
else
{ row = layoutInflater.inflate(R.layout.grid_list3, parent, false);}
只需要那两行中的父和假......
答案 0 :(得分:1)
您可以覆盖getItemViewType(int position)
方法并将条件放在那里。 (if(position%2 == 0)并根据该条件返回视图类型。)当然,您需要声明两种视图类型,并根据您的标准返回正确的视图类型。
在onCreateViewHolder中,您可以检查viewType并为该位置充气正确的布局。