Efficient adapter has java.lang.ClassCastException?

只愿长相守 提交于 2019-12-12 10:05:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!