Sajad Asadi Sajad Asadi - 1 month ago 10
Android Question

get position from RecyclerView.Adapter

I have a recyclerview.Adapter class this is my class :
when i'm pass int position in the MovieViewHolder onCreateViewHolder class parameters thats not works :(

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);
}
}
}


here i want position for even and odd rows :

if ((position % 2) == 0 ){
row = layoutInflater.inflate(R.layout.grid_list3, parent, false);}
else{row = layoutInflater.inflate(R.layout.grid_list3, null);}


but position is still red with cannot resolve error
what can i do in this case?
thanks in advance




EDIT thanks to alex i've got this done :

@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);}


just needed that parent and false in the both of rows ....

Answer

You could override the getItemViewType(int position) method and put your condition there. (if (position % 2 ==0) and return view types based on that condition.) Of course you need to declare two view types and return the right one based on your criteria.

In your onCreateViewHolder you could check the viewType and inflate the right layout for that position.

Comments