Метод LinearLayout адаптера Recyclerview onCreateViewHolder нельзя преобразовать в TextView - PullRequest
1 голос
/ 04 августа 2020

Итак, я просто пытаюсь настроить простой 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 "

Мне сложно понять, что происходит, так как я просто слежу за обучающими материалами в Интернете. Если бы кто-нибудь мог мне помочь, я был бы очень признателен.

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Когда вы выполняете inflater.inflate(R.layout.workout_item, parent, false), вы раздуваете полный макет вашего XML файла. Самый верхний элемент этого XML файла - LinearLayout, поэтому возвращаемый расширенный макет - LinearLayout, а не TextView.

У вас есть два варианта:

  1. Полностью удалите LinearLayout.

Это будет означать, что ваш макет будет содержать только ваш единственный TextView, что сделает ваше преобразование успешным.

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/workout_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    />
Обновите свой ViewHolder, чтобы получить полный макет.

Здесь вы должны обновить WorkoutActivityAdapter.MyViewHolder, чтобы получить полный макет, и использовать view.findViewById(R.id.workout_text_view), чтобы получить TextView из макета. Это было бы целесообразно, если бы у вас было более одного представления в вашем макете.

1 голос
/ 04 августа 2020

Проблема связана с методом onCreateViewHolder.

Вы используете

TextView contactView = (TextView) inflater.inflate(R.layout.workout_item, parent, false);

, но root вид макета workout_item - LinearLayout, и вы не может преобразовать LinearLayout в TextView.

Используйте что-нибудь:

    @Override
    public WorkoutActivityAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View view = inflater.inflate(R.layout.workout_item, parent, false);

        // Return a new holder instance
        WorkoutActivityAdapter.MyViewHolder viewHolder = new WorkoutActivityAdapter.MyViewHolder(view);
        return viewHolder;
    }

и:

public static class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView textView;
    public MyViewHolder (View v) {
        super(v);
        textView = (TextView) v.findViewById(R.id.workout_text_view);
    }
}
...