не отображается RecyclerView в ViewPager2

Рейтинг: 0Ответов: 1Опубликовано: 18.03.2023

значится, я пытаюсь в viewpager2 отобразить ресайклвью, во фрагменте, однако дело не в иьюпаджер ибо его я проверил текствью, и он отображался

код фрагмента до(смотрите комментарии):

class tabfragment : Fragment(R.layout.fragment_tabfragment) {
    private val binding by viewBinding(FragmentTabfragmentBinding::bind)
    private val bd by lazy { notesdb.notedbfunc(requireActivity()).gdao()}
    private val noterep : NoteRepository by lazy { repositoryimp(bd) }
    private val notesdata by lazy { noterep.getnoteslived() }
    private val notes = mutableListOf<note>()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_tabfragment,container,false)
    }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.recyclerviewitem.adapter = recyclerviewclass()
    binding.recyclerviewitem.layoutManager = LinearLayoutManager(requireActivity())
    var noteadapter = recyclerviewclass()
    notesdata.observe(viewLifecycleOwner){
    println(it)
        it.forEach { i ->
            if(i.deleted == false && i.archived == false){
                notes.add(i)
            }
        }
        noteadapter.update(notes)
        notes.clear()
    }


}
}

после:

class tabfragment : Fragment() {
private val bd by lazy { notesdb.notedbfunc(requireActivity()).gdao()}
private val noterep : NoteRepository by lazy { repositoryimp(bd) }
private val notesdata by lazy { noterep.getnoteslived() }
private val notes = mutableListOf<note>()
override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment_tabfragment,container,false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    var recyclerview = view.findViewById<RecyclerView>(R.id.recyclerviewitem)
    recyclerview.adapter = recyclerviewclass()
    recyclerview.layoutManager = LinearLayoutManager(requireActivity())
    var noteadapter = recyclerviewclass()
    notesdata.observe(viewLifecycleOwner){
    println(it)
        it.forEach { i ->
            if(i.deleted == false && i.archived == false){
                notes.add(i)
            }
        }
        noteadapter.update(notes)
        notes.clear()
    }


}
}

ресайклвью, я до этого использовал также во фрагменте и он работал,во вьюпадгер перестал

class recyclerviewclass() :
RecyclerView.Adapter<recyclerviewclass.MyViewHolder>() {
private val array = mutableListOf<note>()
@SuppressLint("NotifyDataSetChanged")
fun update(newlist : List<note>){
    array.clear()
    array.addAll(newlist)
    notifyDataSetChanged()
}
var layouts = mutableListOf<FrameLayout>()
var onbuttonclickfordelete: ((note) -> Unit)? = null
var onbuttonlongclick : ((note) -> Unit)? = null
var onbuttonclick : ((note) -> Unit)? = null
var arrnotes = mutableListOf<note>()
var bool = true
fun invisiblecheckboxs(){
    layouts.forEach {
        it.checkBox.isChecked = false
        it.checkBox.isVisible = false
    }
    arrnotes.clear()
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val layout = itemView.findViewById<FrameLayout>(R.id.layoutnote)

}

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

@SuppressLint("ResourceAsColor", "SuspiciousIndentation")
override fun onBindViewHolder(holder: MyViewHolder, i: Int) {

    layouts.add(holder.layout)
    holder.layout.namenote.setText(array[i].namenote)
    holder.layout.note.setText(array[i].note)
    holder.layout.setOnClickListener {
        if(arrnotes.size >= 1){
            bool = true
            arrnotes.find {
                array[i] == it
            }?.let {
                bool = false
                arrnotes.remove(it)
                if (arrnotes.size == 0){
                    layouts.forEach { i ->
                        i.namenote.width = i.namenote.width + i.checkBox.width
                        i.note.width = i.note.width + i.checkBox.width
                        i.checkBox.isVisible = false
                    }
                }
                holder.layout.checkBox.isChecked = false
                onbuttonclickfordelete?.invoke(it)
            }
            if (bool) {
                arrnotes.add(array[i])
                holder.layout.checkBox.isChecked = true
                onbuttonlongclick?.invoke(array[i])
            }

        }
        else{
            onbuttonclick?.invoke(array[i])
        }
    }
    holder.layout.setOnLongClickListener {
        bool = true
        arrnotes.find {
            array[i] == it
        }?.let {
            bool = false
            arrnotes.remove(it)
            if (arrnotes.size == 0){
                layouts.forEach { i ->
                    i.namenote.width = i.namenote.width + i.checkBox.width
                    i.note.width = i.note.width + i.checkBox.width
                    i.checkBox.isVisible = false
                }
                holder.layout.namenote.width = holder.layout.namenote.width - holder.layout.checkBox.width
                holder.layout.note.width = holder.layout.note.width - holder.layout.checkBox.width
            }
            holder.layout.checkBox.isChecked = false
            onbuttonclickfordelete?.invoke(it)
        }
        if (bool) {
            arrnotes.add(array[i])
            if (arrnotes.size == 1){
                layouts.forEach { i ->
                    i.namenote.width = i.namenote.width - i.checkBox.width
                    i.note.width = i.note.width - i.checkBox.width
                    i.checkBox.isVisible = true
                }
            }
            holder.layout.checkBox.isChecked = true
            onbuttonlongclick?.invoke(array[i])
        }
            return@setOnLongClickListener true
    }
}

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

обьяснение причины ошибки в коментариях к ответу

Ответы

▲ 0Принят

У вас много странного в коде. Очень сбивает несоблюдение конвенций именования - классы должны быть с большой буквы, например. Поверхностно видно 3 проблемы -

  1. Вы в onCreateView одну разметку возвращаете, а в onViewCreated другую используете (через binding). Надо выбрать что-то одно - оба варианта вместе не имеют смысла и не будут работать. Странно, что вообще не падает.
  2. Не факт, что проблема, но layoutManager лучше до адаптера устанавливать.
  3. Вы разные экземпляры адаптера используете. В recyclerviewitem один устанавливаете, а меняете потом другой.