当前位置: 首页 > 知识库问答 >
问题:

具有多个视图类型的RecycerView GridLayoutManager,Viewholder强制转换异常

耿永寿
2023-03-14

因此,我遵循本教程,我有一个带有GridLayoutManager实现的RecycerView。GridLayoutManager有2列。我希望有两个视图类型,所以我使用了两个扩展RecycerView.Viewholder的Viewholder,并且重写了这个方法:getItemViewType(int位置),但是我使用了一个强制转换异常。Logcat显示以下内容:

java.lang.ClassCastException:Adapter.AdapterListItemHome$CommentViewHolder0不能在Adapter.AdapterListItemHome.onBindViewHolder(AdapterListItemHome.onBindViewHolder)处强制转换为Adapter.AdapterListItemHome.java:25)处的Adapter.AdapterListItemHome$CommentViewHolder1

但是我不对CommentViewHolder0和CommentViewHolder1使用强制转换,例如行问题是:

final CommentViewHolder0 vh0 = (CommentViewHolder0)cvh;

这是来自适配器(AdapterListItemHome.java)的代码:

public class AdapterListItemHome extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {
ArrayList<GadgetItem> mListItem;
Context mContext;
private int choice;
public static OnItemClickListener listener;// Define listener member variable
public static final int FIRST_ITEM = 0;
public static final int REST_ITEMS = 1;
/**
 * Defines the listener interface
 */
public interface OnItemClickListener {
    void onItemClick(View itemView, int position);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}

/**
 * view holder - holds the widgets - classical
 */
public class CommentViewHolder1 extends RecyclerView.ViewHolder {
    public ProgressBar pgLoading;
    public TextView tv_title;
    public ImageView imgView;

    //constructor
    public CommentViewHolder1(final View itemView) {
        super(itemView);
        // Find the TextView in the LinearLayout
        tv_title = ((TextView) itemView.findViewById(R.id.namgeItem));
        pgLoading = (ProgressBar) itemView.findViewById(R.id.pbLoadingImage);
        imgView = (ImageView) itemView.findViewById(R.id.imgItem);
        itemView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // Triggers click upwards to the adapter on click
                if (listener != null)
                    listener.onItemClick(itemView, getPosition());
            }
        });
    }
}
/**
 * second viewHolder
 */
public class CommentViewHolder0 extends RecyclerView.ViewHolder {

    public ProgressBar pgLoading;
    public TextView tv_title;
    public ResizableImageView imgView;
    public TextView tv_date;

    //constructor
    public CommentViewHolder0(final View itemView) {
        super(itemView);
        // Find the TextView in the LinearLayout
        tv_title = ((TextView) itemView.findViewById(R.id.namgeItem));
        tv_date = ((TextView) itemView.findViewById(R.id.tv_date));
        pgLoading = (ProgressBar) itemView.findViewById(R.id.pbLoadingImage);
        imgView = (ResizableImageView) itemView.findViewById(R.id.resizable_image);
        imgView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // Triggers click upwards to the adapter on click
                if (listener != null)
                    listener.onItemClick(imgView, getPosition());

            }
        });
    }

}
/*
 * VF: Constructor
 */
public AdapterListItemHome(Context pContext, ArrayList<GadgetItem> pListGadget) {
    this.mContext = pContext;
    this.mListItem = pListGadget;
}

/**
 * Replace the contents of a view (invoked by the layout manager)
 * @param viewGroup
 * @param ViewType
 * @return
 */

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int ViewType){
    View v;
    //Log.d("bill", "viewtype = " + String.valueOf(ViewType));
    switch(ViewType){
        case REST_ITEMS:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, viewGroup, false);
            CommentViewHolder1 cvh1 = new CommentViewHolder1(v);
            return cvh1;
        case FIRST_ITEM:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item_home, viewGroup, false);
            CommentViewHolder0 cvh0 = new CommentViewHolder0(v);
            return cvh0;
        default:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, viewGroup, false);
            CommentViewHolder1 cvh2 = new CommentViewHolder1(v);
            return cvh2;
    }
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder cvh, int position) {

    Transformation transformation;
    GadgetItem item;

    switch ( cvh.getItemViewType () ){

        case REST_ITEMS:

            final CommentViewHolder1 vh1 = (CommentViewHolder1)cvh;
            item = mListItem.get(position);
            vh1.tv_title.setText(item.gadget_title);
            vh1.pgLoading.setVisibility(View.VISIBLE);
            vh1.imgView.setImageDrawable(null);
            /**
             * clicking on the image view
             */
             transformation = new Transformation() {

                @Override
                public Bitmap transform(Bitmap source) {
                    int targetWidth = vh1.imgView.getWidth();
                    double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                    int targetHeight = (int) (targetWidth * aspectRatio);
                    // Bitmap result = Bitmap.createScaledBitmap(source,
                    // targetWidth,
                    // targetHeight, false);
                    Bitmap result = scaleAndCropImage(source, 300);
                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
                    return result;
                }

                @Override
                public String key() {
                    return "transformation" + " desiredWidth";
                }
            };
            Picasso.with(mContext).load(item.gadget_image).into(vh1.imgView, new Callback() {
                @Override
                public void onError() {
                }

                @Override
                public void onSuccess() {
                    vh1.pgLoading.setVisibility(View.GONE);
                }

            });

        case FIRST_ITEM:

            final CommentViewHolder0 vh0 = (CommentViewHolder0)cvh;
            item = mListItem.get(position);
            vh0.tv_title.setText(item.gadget_title);
            vh0.pgLoading.setVisibility(View.VISIBLE);
            vh0.imgView.setImageDrawable(null);
            vh0.tv_date.setText(item.gadget_pubDate);
            /**
             * clicking on the image view
             */
             transformation = new Transformation() {

                @Override
                public Bitmap transform(Bitmap source) {
                    int targetWidth = vh0.imgView.getWidth();
                    double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                    int targetHeight = (int) (targetWidth * aspectRatio);
                    // Bitmap result = Bitmap.createScaledBitmap(source,
                    // targetWidth,
                    // targetHeight, false);
                    Bitmap result = scaleAndCropImage(source, 300);
                    if (result != source) {
                        // Same bitmap is returned if sizes are the same
                        source.recycle();
                    }
                    return result;
                }

                @Override
                public String key() {
                    return "transformation" + " desiredWidth";
                }
            };
            Picasso.with(mContext).load(item.gadget_image).into(vh0.imgView, new Callback() {
                @Override
                public void onError() {

                }

                @Override
                public void onSuccess() {
                    vh0.pgLoading.setVisibility(View.GONE);
                }

            });
    }
}
// Return the size of  dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return mListItem.size();
}
/*  (non-Javadoc)
 *  VF: creating a item to show
 */

Bitmap scaleAndCropImage(Bitmap image, int height) {
    float ratio = (float) (height) / (float) image.getHeight();
    int width = (int) ((float) image.getWidth() * ratio);
    return ScalingUtilities.createScaledBitmap(image, width, height, ScalingUtilities.ScalingLogic.CROP);
}

@Override
public int getItemViewType(int position) {
    int viewType;

        if (position == 1)
            viewType = FIRST_ITEM;
        else
            viewType = REST_ITEMS;


    return viewType;
    }
 }

这是RecycerView正在实现的片段

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent , Bundle savedInstanceState) {
    if(parent == null)
        return null;
    if(v != null)
        return v;
    //initialize the view v
    v = inflater.inflate(R.layout.fragment_list_item_home, parent , false);
    //initialization Recycler view
    mRecyclerView = (RecyclerView) v.findViewById(R.id.listItem_home);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new GridLayoutManager(getActivity(),2);
    mRecyclerView.addItemDecoration(new DividerItemDecoration(4,2));
    mRecyclerView.getItemAnimator().setMoveDuration(5000);
    mRecyclerView.setLayoutManager(mLayoutManager);
    if(mAdapter == null) {
                //setting the adapter
                mAdapter = new AdapterListItemHome(getActivity(),mList);
                mRecyclerView.setAdapter(mAdapter);

                v.setFocusableInTouchMode(true); //focusing when touching
                v.requestFocus(); //To force focus to a specific view
                mAdapter.setOnItemClickListener(new AdapterListItemHome.OnItemClickListener() {

                    @Override
                    public void onItemClick(View view, int position) {
                        onListViewItemClick(position);
                    }
                });
            }

共有1个答案

郁明诚
2023-03-14

这段代码对我来说很好:

public class AdapterListItemHome extends RecyclerView.Adapter<AdapterListItemHome.MainHolder>  {
ArrayList<GadgetItem> mListItem;
Context mContext;
public static OnItemClickListener listener;// Define listener member variable
public static final int FIRST_ITEM = 0;
public static final int REST_ITEMS = 1;
/**
 * Defines the listener interface
 */
public interface OnItemClickListener {
    void onItemClick(View itemView, int position);
}
// Define the method that allows the parent activity or fragment to define the listener
public void setOnItemClickListener(OnItemClickListener listener) {
    this.listener = listener;
}
public class MainHolder extends RecyclerView.ViewHolder {

    public MainHolder(View itemView){
        super(itemView);
    }
}
/**
 * view holder - holds the widgets 
 */
public class CommentViewHolder1 extends MainHolder {
    public ProgressBar pgLoading;
    public TextView tv_title;
    public ImageView imgView;

    //constructor
    public CommentViewHolder1(final View itemView) {
        super(itemView);
        // Find the TextView in the LinearLayout
        tv_title = ((TextView) itemView.findViewById(R.id.namgeItem));
        pgLoading = (ProgressBar) itemView.findViewById(R.id.pbLoadingImage);
        imgView = (ImageView) itemView.findViewById(R.id.imgItem);
        itemView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // Triggers click upwards to the adapter on click
                if (listener != null)
                    listener.onItemClick(itemView, getPosition());
            }
        });
    }   
}
/**
 * second viewHolder
 */
public class CommentViewHolder0 extends MainHolder {

    public ProgressBar pgLoading;
    public TextView tv_title;
    public ResizableImageView imgView;
    public TextView tv_date;

    //constructor
    public CommentViewHolder0(final View itemView) {
        super(itemView);
        // Find the TextView in the LinearLayout
        tv_title = ((TextView) itemView.findViewById(R.id.namgeItem_home));
        tv_date = ((TextView) itemView.findViewById(R.id.tv_date));
        pgLoading = (ProgressBar) itemView.findViewById(R.id.pbLoadingImage_home);
        imgView = (ResizableImageView) itemView.findViewById(R.id.resizable_image);
        imgView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                // Triggers click upwards to the adapter on click
                if (listener != null)
                    listener.onItemClick(imgView, getPosition());

            }
        });
    }

}
public AdapterListItemHome(Context pContext, ArrayList<GadgetItem> pListGadget,ArrayList<String> pDateList) {
    this.mContext = pContext;
    this.mListItem = pListGadget;
    this.mDateList = pDateList;
    p = new Picasso.Builder(mContext)
            .memoryCache(new LruCache(cacheSize))
            .build();
}

/**
 * Replace the contents of a view (invoked by the layout manager)
 */
@Override
public MainHolder onCreateViewHolder(ViewGroup viewGroup, int ViewType){
    View v
    switch(ViewType){
        case REST_ITEMS:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, viewGroup, false);
            CommentViewHolder1 cvh1 = new CommentViewHolder1(v);
            return cvh1;
        case FIRST_ITEM:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item_home, viewGroup, false);
            CommentViewHolder0 cvh0 = new CommentViewHolder0(v);
            return cvh0;
        default:
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, viewGroup, false);
            CommentViewHolder1 cvh2 = new CommentViewHolder1(v);
            return cvh2;
    }
}

@Override
public void onBindViewHolder(MainHolder cvh, int position) {

    switch ( cvh.getItemViewType () ){

        case REST_ITEMS:

            final CommentViewHolder1 vh1 = (CommentViewHolder1)cvh;
            GadgetItem item1 = mListItem.get(position);
            vh1.tv_title.setText(fixTitleText(20, item1.gadget_title) + item1.gadget_price);
            vh1.pgLoading.setVisibility(View.VISIBLE);
            vh1.imgView.setImageDrawable(null);
            final int y = 200;
            final int x = 200;
            //picasso
            p.with(mContext).load(item1.gadget_image).resize(x, y).centerCrop().into(vh1.imgView, new Callback() {
                @Override
                public void onError() {
                }

                @Override
                public void onSuccess() {
                    vh1.pgLoading.setVisibility(View.GONE);
                }

            });
            break;
        case FIRST_ITEM:
            final CommentViewHolder0 vh0 = (CommentViewHolder0)cvh;
            GadgetItem item = mListItem.get(position);
            vh0.tv_title.setText(fixTitleText(63, item.gadget_title) + item.gadget_price);
            vh0.pgLoading.setVisibility(View.VISIBLE);
            vh0.imgView.setImageDrawable(null);
            String dateTime = fixdateTime(item.gadget_pubDate);
            String date = null;
            try {
                date = calculateDate(dateTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            vh0.tv_date.setText(date + " " + dateTime);

            final int y1 = 335;
            final int x1 = 400;
            //picasso
            p.with(mContext).
                    load(item.gadget_image).resize(x1, y1).centerCrop().into(vh0.imgView, new Callback() {
                @Override
                public void onError() {

                }

                @Override
                public void onSuccess() {
                    vh0.pgLoading.setVisibility(View.GONE);
                }

            });

            break;
    }
}
// Return the size of  dataset (invoked by the layout manager)
@Override
public int getItemCount() {

    return mListItem.size();
}
/*  (non-Javadoc)
 *  VF: creating a item to show
 */
@Override
public int getItemViewType(int position) {
    int viewType;

        if (position == 0 || (!(mDateList.get(position).equals(mDateList.get(position -1 )))))
            viewType = FIRST_ITEM;
        else
            viewType = REST_ITEMS;

    return viewType;
}
}
 类似资料:
  • 强制类型转换 隐式类型转换:隐式类型转换又称为自动类型转换,隐式类型转换可分为三种:算术转换、赋值转换和输出转换。 显式类型转换:显式类型转换又称为强制类型转换,指的是使用强制类型转换运算符,将一个变量或表达式转化成所需的类型,这种类型转换可能会造成数据的精度丢失。 数据有不同的类型,不同类型数据之间进行混合运算时必然涉及到类型的转换问题。 转换的方法有两种: 自动转换(隐式转换):遵循一定的规则

  • 例外情况: java.lang.ClassCastException:com.interconnect.library.gcm.util.checkplayServices(util.java:96),com.interconnect.library.gcm.regiseter.handleRegister(regiseter.java:53),com.interconnect.library.g

  • 问题内容: 我试图实现一个排序和未排序的数组列表。两者都扩展了一个名为AbstractArrayMyList的类,其中包含常见的操作/实现- toString,clear等。 这是我的AbstractArrayMyList代码(它实现了我定义的通用接口) 我选择对elementData进行保护,以便可以对已排序和未排序的专用数组列表进行访问并对其执行操作。这是我的排序数组列表的声明/代码 所有这些

  • 我模拟了Jsch()类,并在下面的方法中获得了类强制转换异常。 原始方法。 联机获取Mockito异常。 例外情况: java.lang.ClassCastException:com.jcraft.jsch。频道$MockitoMock$1983492043不能转换为com.jcraft.jsch.ChannelSftp 测试用例调用方法。

  • 问题内容: 尝试将结果集强制转换为映射类时,我收到了hibernate类的类强制转换异常…我能够查看返回的结果集中的数据…但是它以Object []的形式返回我可以将Object []设置为List …我可以正确地进行hibernate映射吗?我从查询中获取了正确的数据,但映射不正确… 映射 映射类 参加班 主要 问题答案: 对于测试,我建议您在产生类强制转换异常的语句周围放置一个try-catc

  • 调用AffineTransform: 它驻留在自定义形状类(YingYang)中。 当我进行调用时,当我试图从绘图面板或在类本身(如果我将返回类型更改为YingYang)中将它转换回一个YingYang时,我会得到一个类转换异常。 java.lang.ClassCastException:java.awt.Geom.Path2D$Double不能强制转换为Animation.Yingyang 任何