【发布时间】:2020-08-03 23:09:22
【问题描述】:
所以我只是想设置一个简单的 Recyclerview 来显示数组中的字符串。这是我设置的适配器:
package com.example.workoutapp1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class WorkoutActivityAdapter extends RecyclerView.Adapter<WorkoutActivityAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public MyViewHolder (TextView v) {
super(v);
textView = (TextView) v.findViewById(R.id.workout_text_view);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public WorkoutActivityAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public WorkoutActivityAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
TextView contactView = (TextView) inflater.inflate(R.layout.workout_item, parent, false);
// Return a new holder instance
WorkoutActivityAdapter.MyViewHolder viewHolder = new WorkoutActivityAdapter.MyViewHolder(contactView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
@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]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
}
workout_item.xml 是一个简单的线性布局,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp" >
<TextView
android:id="@+id/workout_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
每次我运行此程序时,应用程序都会崩溃,因为在我尝试膨胀自定义布局时出现了一个致命异常:
“java.lang.ClassCastException: android.widget.LinearLayout 无法转换为 android.widget.TextView”
我无法理解发生了什么,因为我只是按照在线教程进行操作。 如果有人可以帮助我,将不胜感激。
【问题讨论】:
标签: java android android-layout android-recyclerview