Reputation: 9093
I'm using Adapter with 3 types of Views
public class MyAdapter extends ArrayAdapter<MyClass> {
@Override
public int getViewTypeCount() {
return 3;
}
//...
}
And it appears that sometimes wrong types of Views are passed to getView. Indeed docs warn about it:
Note: You should check that this view is non-null and of an appropriate type before using.
How should I check if a view is of an appropriate type before using?
Should I just check by findViewById if it contains some id from appropriate xml? But does it really check "if a view is of an appropriate type"?
EDIT: Answers so far seems to not miss my question so to clarify:
Yeah I'm using getItemViewType
but as I have 3 types of Views, then sometimes convertView
in getView has wrong type (not the View which was inflated for the getItemViewType
) and cannot be converted to the right one - the question is not about how to check which View SHOULD be returned (and this is covered by "bigdestroyer" answer), but if the View passed to getView can be reused (and in my case it cannot).
Upvotes: 1
Views: 777
Reputation: 26034
"Appropriate type" means that you have to check in getView
method the type of the convertView
in order to return a custom View
or another one.
You can override getItemViewType
method of BaseAdapter
. For instance:
public int getItemViewType(int position) {
MyItem item = getItem(position);
return item.getViewType();
}
and:
public View getView(int position, View convertView, ViewGroup parent) {
int viewType = getItemViewType(position);
if (convertView != null) {
if (viewType == 1) return recycleViewOfType1(position, convertView);
if (viewType == 2) return recycleViewOfType2(position, convertView);
}
else {
if (viewType == 1) return newViewOfType1(position);
if (viewType == 2) return newViewOfType2(position);
}
return null;
}
Upvotes: 2
Reputation: 2559
You can use getItemViewType()
method to determine view type before creating/ reusing views in getView()
method.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int type = getItemViewType(position);
if(type == 1){
}else {
}
}
check this tutorial for more info
Upvotes: 0