I have to show a list with different type of Views. So I have to define a ListView with an Adapter where I have to inflate multiple views. I have gone through example given,
You can do that by overriding the Methods getViewCount()
and getItemViewType(int position)
In the first you just return the amount of different Views you have.
In the second you return a unique Identifier for each different View.
In your getView()
Method you check then for the View Type and inflate the right Layout for it.
More info about that topic: Android ListView with different layouts for each row
Android ListView with different layouts for each row
You can look this example adapter. getViewTypeCount method return your different type row. getItemViewType method, if position equals 0 inflate first row layout else inflate other row layout. You can customize this code example.
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
/**
* Created by MustafaS on 9.2.2015.
*/
public class CustomArrayAdapter extends ArrayAdapter<YourModel> {
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
}
else {
return 1;
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
if (type == 0) {
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.listview_first_row, parent, false);
viewHolderFirst = new ViewHolderFirst();
convertView.setTag(viewHolderFirst);
}
else {
viewHolderFirst = (ViewHolderFirst) convertView.getTag();
}
}
else {
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.listview_other_row, parent, false);
viewHolder = new ViewHolder();
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
}
return convertView;
}
protected class ViewHolderFirst {
private RunnableViewPager pager;
private CircleIndicator indicator;
}
protected class ViewHolder {
private ImageView imageviewRestaurant;
private TextView textviewRestaurantName;
private TextView textviewType;
private TextView textviewPrice;
private TextView textviewDistance;
private ImageView imageviewCall;
private ImageView imageviewCalendar;
}
}
This is what you need to use when you different types of Views inside a ListView or RecyclerView :-
getItemViewType() and getViewTypeCount()
First you need to use getViewTypeCount() and return the number of unique views you need inside your List. Then override getItemViewType() and return the View type based on the whatever condition you want your views to change on inside the ListView.
Hope it will help.