java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget

宝剑锋从磨砺出,梅花香自苦寒来。这篇文章主要讲述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 36MyViewHolder 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行找不到问题出在哪里。
答案【java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget】你没有正确地膨胀视图 onCreateViewHolder . 应该是这样的
View view; LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); view = layoutInflater.inflate(R.layout.my_text_view,parent,false); return new MyAdapter.MyViewHolder(view);


    推荐阅读