问题
After watching here I try to implement my own efficient adapter,
My ViewHolder class almost same:
static class ViewHolder {
ImageButton button;
TextView txtView;
}
getView method look like:
private void getView(...) {
if(convertView == null) {
convertView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.linear_container,
parent, false);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
// erro line
holder = (ViewHolder) convertView.getTag();
}
LinearLayout llCustomImgViewContainer = (LinearLayout) convertView
.findViewById(R.id.llContainer);
llCustomImgViewContainer.setTag(viewPosition);
return converView;
}
but here once new view started to draw, it give me error
D/AndroidRuntime( 748): Shutting down VM W/dalvikvm( 748): threadid=1: thread exiting with uncaught exception (group=0x412a4300) E/AndroidRuntime( 748): FATAL EXCEPTION: main E/AndroidRuntime( 748): java.lang.ClassCastException: java.lang.Integer cannot be cast to com.droid.test.widget.customListView$CustomBaseAdapter$ViewHolder
any one have idea what is wrong here?
回答1:
It seems that at first with
convertView.setTag(holder);
line you are setting the tag(which is holder) associated with this view but later with
llCustomImgViewContainer.setTag(viewPosition);
you are setting viewPosition as a tag. Then probably in
holder = (ViewHolder) convertView.getTag();
your code trying to cast Integer to ViewHolder and throws a java.lang.ClassCastException.
If I'm not wrong and this is the structure of the "linear_container" layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/llContainer">
<!-- some views -->
</LinearLayout>
The view returned from
LayoutInflater.from(parent.getContext()).inflate(R.layout.linear_container,parent,false);
and the view returned from
convertView.findViewById(R.id.llContainer);
should be same.
回答2:
You're setting an int instead of the view :
llCustomImgViewContainer.setTag(viewPosition);
When you use setTag, you save the given object (viewPosition), in the calling object (llCustomImgViewContainer).
Remove the last line :
llCustomImgViewContainer.setTag(viewPosition);
来源:https://stackoverflow.com/questions/18382443/efficient-adapter-has-java-lang-classcastexception