java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget相关的知识,希望对你有一定的参考价值。
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { // <-- line 9
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView textView;
public MyViewHolder(View v) {
super(v);
textView = (TextView) v.findViewById(R.id.mTextView);
this.textView = textView;
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false); // <-- line 36
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.textView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
这是MyAdapter类的代码,当我运行它时,该应用程序一直关闭,所以我检查了Logcat,它说:"这是我的应用程序。
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.t5online.chat.hanbattalk, PID: 593
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
at com.t5online.chat.hanbattalk.MyAdapter.onCreateViewHolder(MyAdapter.java:36)
at com.t5online.chat.hanbattalk.MyAdapter.onCreateViewHolder(MyAdapter.java:9)
但是,我在第36行和第9行找不到问题出在哪里。
答案
你没有正确地膨胀视图 onCreateViewHolder
. 应该是这样的
View view;
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
view = layoutInflater.inflate(R.layout.my_text_view,parent,false);
return new MyAdapter.MyViewHolder(view);
以上是关于java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget的主要内容,如果未能解决你的问题,请参考以下文章