WasTabon
@WasTabon

Адаптер для Recycler View не работает?

Спрашивал у чата гпт несколько раз, говорил что все норм, так же переделывал с нуля с его помощью, делал то же самое. Но при запуске элементы в список не добавляются

Вот код адаптера
class MusicAdapter : RecyclerView.Adapter<MusicAdapter.MusicViewHolder>() {

    private val list = ArrayList<Music>()

    fun setList(newList: List<Music>) {
        list.clear()
        list.addAll(newList)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
        val itemView = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_music, parent, false)
        return MusicViewHolder(itemView)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        val element = list[position]
        holder.bind(element)
    }

    inner class MusicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val musicName: TextView = itemView.findViewById(R.id.musicName)
        private val musicAuthor: TextView = itemView.findViewById(R.id.musicAuthor)

        fun bind(item: Music) {
            musicName.text = item.name
            musicAuthor.text = item.author
        }
    }
}


вот код самого фрагмента

class MusicListFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: MusicAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_music_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.musicListId)

        val musicList = ArrayList<Music>()
        musicList.add(Music("Ruckus", "Sxmpra"))
        musicList.add(Music("Override", "KSLV-NOH"))

        // Создайте адаптер и установите его в ListView
        adapter = MusicAdapter()
        adapter.setList(musicList)
        recyclerView.adapter = adapter
    }
}


и вот код xml

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/musicListId"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginHorizontal="15dp"
        tools:listitem="@layout/item_music"
        tools:itemCount="2"/>
  • Вопрос задан
  • 77 просмотров
Решения вопроса 2
@cyBEERkotleta
Верно, для RecyclerView нужно задать менеджера разметки (LayoutManager). Это можно сделать не только через xml, но и через код, если, например, есть необходимость корректировать его настройки, или вообще тип LayoutManager во время выполнения программы.
Ответ написан
Комментировать
WasTabon
@WasTabon Автор вопроса
Методом проб и ошибок понял что в RecyclerView xml надо добавить
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы