RelativeLayout无法转换为ImageView?

时间:2019-03-27 01:59:26

标签: android android-relativelayout

我目前正在构建一个twitter客户端,在这个java类中,我有3个我不确定如何解决的错误。我尝试事先设置ImageView类型,但是没有用。例如;我有ivProfileImage = (ImageView),但没有成功。我尝试使用谷歌搜索多个解决方案,但都无济于事。不知道问题出在Java类中还是其他原因?

收到错误消息:

java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.ImageView

我的代码:

package com.codepath.apps.restclienttemplate;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import java.util.*;
import com.bumptech.glide.*;
import com.codepath.apps.restclienttemplate.models.Tweet;


public class TweetsAdapter extends RecyclerView.Adapter<TweetsAdapter.ViewHolder> {
    private Context context;
    private List<Tweet> tweets;

    public TweetsAdapter(Context context, List<Tweet> tweets) {
        this.context = context;
        this.tweets = tweets;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public ImageView ivProfileImage;
        public TextView tvScreenName;
        public TextView tvBody;

        public ViewHolder(View itemView) {
            super(itemView);
            ivProfileImage = itemView.findViewById(R.id.ivProfileimage);
            tvScreenName = itemView.findViewById(R.id.tvScreenName);
            tvBody = itemView.findViewById(R.id.tvBody);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_tweet, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Tweet tweet = tweets.get(position);
        holder.tvBody.setText(tweet.body);
        holder.tvScreenName.setText(tweet.user.screenName);
        Glide.with(context).load(tweet.user.profileImageUrl).into(holder.ivProfileImage);
    }


    @Override
    public int getItemCount() {
        return tweets.size();
    }
}

2 个答案:

答案 0 :(得分:1)

问题很明显,您尝试将RelativeLayout投射到ImageView

请确保R.id.ivProfileimage的ID为ImageView

答案 1 :(得分:0)

这是classcastexeption,因为您不能将不同的类相互引用。