Не удается разрешить функцию RecyclerView setLayoutManager ()

#android #android-studio #android-recyclerview

#Android #android-studio #android-recyclerview

Вопрос:

Итак, я следую этому руководству: https://www.youtube.com/watch?v=18VcnYN5_LM

Все работает отлично до самого конца, где он устанавливает менеджер компоновки. Android Studio сообщает мне, что этот метод не может быть разрешен. Поскольку это, похоже, также используется в других руководствах и даже на официальной странице: https://developer.android.com/guide/topics/ui/layout/recyclerview Интересно, что я сделал не так? Я предполагаю, что я что-то где-то забыл, но я не могу понять, что. Уже смотрел видео 3 раза.

Было бы здорово, если бы кто-нибудь мог мне помочь.

Мой код:

Основная деятельность

 package com.hkr.Views;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.hkr.R;
import com.hkr.Views.RecyclerViewDevices.DevRecViewAdapter;

public class MainActivity extends AppCompatActivity {
    String stringDevices[];
    RecyclerView devices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        stringDevices = getResources().getStringArray(R.array.devices); //Test devices in String ressource file. Replace with json!
        devices = findViewById(R.id.RecyclerViewDevices);

        DevRecViewAdapter adapter = new DevRecViewAdapter(this, stringDevices);
        devices.setAdapter(adapter);
        adapter.setLayoutManager(new LinearLayoutManager(this));
    }
}
  

Основная деятельность XML

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Views.MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/RecyclerViewDevices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="157dp"
        tools:layout_editor_absoluteY="240dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
  

device_row.xml

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@ id/DevName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Device Name"
                android:textSize="24sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
  

DevRecViewAdapter

 package com.hkr.Views.RecyclerViewDevices;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.hkr.R;

public class DevRecViewAdapter extends RecyclerView.Adapter<DevRecViewAdapter.DevViewHolder> {

    String names[];
    Context c;

    public DevRecViewAdapter(Context context, String devicenames[])
    {
        c=context;
        names=devicenames;
    }

    @NonNull
    @Override
    public DevViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(c);
        View view = inflater.inflate(R.layout.device_row, parent, false);
        return new DevViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DevViewHolder holder, int position) {
        holder.DevName.setText(names[position]);

    }

    @Override
    public int getItemCount() {
        return names.length;
    }


    public class DevViewHolder extends RecyclerView.ViewHolder{

        TextView DevName;

        public DevViewHolder(@NonNull View itemView) {
            super(itemView);
            DevName = itemView.findViewById(R.id.DevName);
        }
    }
}
  

Комментарии:

1. установите layout manager на устройства (RecyclerView), а не на адаптер RecyclerView.

Ответ №1:

У адаптера нет диспетчера компоновки, у RecyclerView есть, поэтому вам нужно установить диспетчер компоновки на RV

 LinearLayoutManager layoutManager = LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL) // or vertical whatever you want
device.setLayoutManager(layoutManager);
  

должно работать

вы также можете установить диспетчер компоновки в файле xml с помощью

 app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="horizontal"
  

в теге просмотра recycler

Комментарии:

1. Потрясающе, это сработало как шарм. Большое вам спасибо за вашу помощь.