无法将ViewHolder投射到自定义视图

时间:2019-08-05 23:27:21

标签: android android-recyclerview android-adapter

我正在尝试使用适配器显示不同的视图,但是在编译时出现错误,因为我无法将holder投射到sendMessageHolder或RecievedMessageHolder

@Override
 //here i got a problem that the type of return is incompatible with what the method should return
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;

    if (viewType == MESSAGE_SENT) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_message_sent_by_me, parent, false);
        return new SentMessageHolder(view);
    } else if (viewType == MESSAGE_RECEIVED) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.activity_message_sent_by_someone_else, parent, false);
        return new ReceivedMessageHolder(view);
    }

    return null;
}


@Override
    public void onBindViewHolder(final MessageAdapter.MyViewHolder holder, int position) {
        final Message message = myMessagetList.get(position);

        switch (holder.getItemViewType()) {
            case MESSAGE_SENT:
               //here there is a problem of incompatible casting
                ((SentMessageHolder) holder).bind(message);
                break;
            case MESSAGE_RECEIVED:
                 //and also here
                ((ReceivedMessageHolder) holder).bind(message);
        }
    }

private class SentMessageHolder extends RecyclerView.ViewHolder {
    TextView messageText;

    SentMessageHolder(View itemView) {
        super(itemView);
        messageText = itemView.findViewById(R.id.text_message_body);
    }

    void bind (Message message) {
        messageText.setText(message.getMessage());
    }
}

我不明白为什么?

1 个答案:

答案 0 :(得分:0)

  

我正在尝试使用适配器显示不同的视图,但是在编译时出现错误,因为我无法将holder投射到sendMessageHolder或RecievedMessageHolder

这是因为以下行:

@Override
public void onBindViewHolder(final MessageAdapter.MyViewHolder holder, int position) {

    ...
}

专门将holder参数限制为MessageAdapter.MyViewHolder的实例。应该是RecyclerView.ViewHolder,类似这样:

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

  ...

}