【问题标题】:how to fix this thing in Recycler View in Kotlin Android如何在 Kotlin Android 的 Recycler View 中修复这个问题
【发布时间】:2021-01-30 23:05:46
【问题描述】:

我正在尝试在我的回收站视图中显示笔记。笔记正文是这样的: 一个文本视图中的注释标题 注意标题下方其他文本视图中的内容

因此,这将显示在一个项目中,然后在下一个项目中显示下一个注释。但问题是, 一项包含注释标题,另一项包含其内容。

这是我的 NotesAdapter 类:

class NotesAdapter(private var noteView: ArrayList<String>):
    RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {

    inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)

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

   override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    //Set data here

       holder.itemView.apply {
          note_title_TV.text = noteView[position]
       
          note_content_TV.text = noteView[position]
       }

   }

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

我的主要活动类(这个类也包含我的 firebase 代码,因为我正在从那里读取数据并将其存储到列表中):

class HomeActivity : AppCompatActivity() {

    var nList = ArrayList<String>();

    private lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: RecyclerView.Adapter<*>
    private lateinit var viewManager: RecyclerView.LayoutManager

    val rootReference = Firebase.database.reference //app root in firebase database
    val currentUser = FirebaseAuth.getInstance().currentUser
    val uid = currentUser?.uid.toString()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        //Show user's name in welcome message
        //get the name of user from firebase
        val nameFromFirebase: FirebaseDatabase = FirebaseDatabase.getInstance()


        var nameReference = rootReference.child("users").child(uid).child("name")
        nameReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val result = snapshot.value
                tv_User_Name.text = result.toString()
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

        })

        btn_createNote.setOnClickListener {
            Intent(this, AddNoteActivity::class.java).also {
                startActivity(it)
            }
        }

        //Read notes from database
        readNotesFromFirebaseDatabase()

        //Updating Layout to display notes in RecyclerView
        recyclerView = findViewById<RecyclerView>(R.id.rv_displayNotesInRecyclerView)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager=LinearLayoutManager(this)

        //RecyclerView Adapter being passed the notes list
        val adapter = NotesAdapter(nList)
        rv_displayNotesInRecyclerView.adapter = adapter

        }


    fun readNotesFromFirebaseDatabase(){
        val noteReference = rootReference.child("users").child(uid).child("Notes")
        noteReference.addValueEventListener(object:ValueEventListener{

            override fun onDataChange(snapshot: DataSnapshot) {
                val noteContent = snapshot.child("noteContent").getValue(String::class.java)
                val noteTitle = snapshot.child("noteTitle").getValue(String::class.java)


                //Add Notes to the ArrayList of Notes
                nList.add(noteTitle.toString())
                nList.add(noteContent.toString())
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }
        })

    }
}

Note_item XML 布局文件:

<?xml version="1.0" encoding="UTF-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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="wrap_content">


    <androidx.cardview.widget.CardView
        android:id="@+id/prompt_cardview"
        android:layout_width="390dp"
        android:layout_height="89dp"

        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:minHeight="120dp"
        app:cardCornerRadius="15dp"
        app:cardElevation="3dp"
        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="384dp"
            android:layout_height="match_parent"
            android:minHeight="120dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:id="@+id/note_title_TV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="8dp"
                android:fontFamily="@font/lato"
                android:lineHeight="22dp"
                android:text="Title"
                android:textAlignment="gravity"
                android:textColor="#4F4B4B"
                android:textSize="18sp"
                android:textStyle="bold"
                android:paddingLeft="2dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.037"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintVertical_bias="0.0" />

            <TextView
                android:id="@+id/note_content_TV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:layout_marginStart="12dp"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="8dp"
                android:fontFamily="@font/lato"
                android:paddingLeft="5dp"
                android:lineHeight="14dp"
                android:singleLine="false"
                android:text="@string/some_comments_are_here_to_stay_you_know"
                android:textAlignment="center"
                android:textColor=" #877B7B"
                android:textSize="12sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/note_title_TV"
                app:layout_constraintVertical_bias="0.0" />

            <ImageButton
                android:id="@+id/btn_edit"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@drawable/round_button_edit"
                android:src="@drawable/icon_btn_edit"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toStartOf="@+id/btn_delete"
                app:layout_constraintHorizontal_bias="0.972"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/note_content_TV"
                app:layout_constraintVertical_bias="1.0" />

            <ImageButton
                android:id="@+id/btn_delete"
                android:layout_width="25dp"
                android:layout_height="25dp"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:background="@drawable/round_button_delete"
                android:src="@drawable/icon_btn_delete"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.983"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/note_content_TV"
                app:layout_constraintVertical_bias="1.0" />

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

我还做了一个笔记课(如果有帮助的话):

class Note (val noteContent:String , val noteTitle: String) {

}

这是我的 Firebase 数据库注释条目,1:https://i.stack.imgur.com/bixCW.png

现在,我得到了这个输出,2: https://i.stack.imgur.com/VV7l7.png

P.S 我知道有一些类似这样的帖子:How to create Multiple View Type in Recycler View 但它们是用 Java 编写的,我在这里转换时遇到了困难。

【问题讨论】:

  • 您的代码发生了一些事情。首先查看nlist ArrayList。在readNotesFromFirebaseDatabase() 中,您将标题和内容分配给单独的条目。在onBindViewHolder() 中,您将ArrayList 中的单个值分配给两个TextViews。您需要关联标题和内容,并确保正确分配 TextViews。就目前而言,每个标题都与每个内容不同,您正在看到结果。将应用程序置于调试模式并查看这两个区域,您应该会明白我的意思。
  • @Cheticamp 感谢您查看代码。但是问题解决了。

标签: firebase kotlin firebase-realtime-database android-recyclerview


【解决方案1】:

问题解决了。

将 ArrayList 从 String 更改为 Note 在主活动类中,编辑了这段代码:

//Add Notes to the ArrayList of Notes

var note : Note

note.noteContent = noteTitle.toString()
 note.noteTitle = noteTitle.toString()

在 NotesAdapter 类中(发布完整正确的代码):

class NotesAdapter(private var noteView: ArrayList<Note>):
    RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {

    inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)

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

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        //Set data here

       holder.itemView.apply {
           note_title_TV.text = noteView[position].noteContent

           note_content_TV.text = noteView[position].noteTitle
       }

    }

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


}

【讨论】:

    【解决方案2】:

    试试这个:

    创建一个包含 2 个变量的模型类

    class Notes{
       val title: String = ""
       val content: String = ""
    }
    

    之后使用该模型类而不是 String 创建一个数组列表,如下所示:

     val list: MutableList<Notes> = Notes()
     val nots : Notes = Notes()
     notes.title = "test"
     notes.content = "Good Work!"
     list.add(notes)
    

    创建列表后,将该列表传递给适配器,您就可以开始了

    class NotesAdapter(private var list: ArrayList<Note>):
         RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
    
         inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
    
         override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
             val noteView : View = LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
             return MyViewHolder(noteView)
         }
    
         override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    
            holder.itemView.apply {
                note_title_TV.text = list[position].title
                note_content_TV.text = list[position].content
            }
         }
    
         override fun getItemCount(): Int {
             return list.size
         }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多