위에 글에서 프로젝트 등록을 끝냈다면
1) RecyclerView 생성
<?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"
android:background="@color/theme_layout_color"
tools:context=".CommentActivity">
<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:text="방명록"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="@id/line"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="35dp"
android:background="@color/grey"
app:layout_constraintStart_toStartOf="@id/titleTextView"
app:layout_constraintTop_toBottomOf="@id/titleTextView" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/commentRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/line"
app:layout_constraintStart_toStartOf="@id/line"
app:layout_constraintTop_toTopOf="@id/line" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:backgroundTint="@color/grey"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:src="@drawable/icon_add" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:backgroundTint="#22C8E4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@id/addButton"
android:src="@drawable/icon_reset" />
</androidx.constraintlayout.widget.ConstraintLayout>
2) 해당 item layout 설정
3) Firestore 필드 이름과 같이 recyclerView Item 생성
- firestore의 타입과 같게 생성한다.
//ItemLayout.kt
class ItemLayout(val name: String, val comment:String)
4) adapter 생성
//ArticleAdapter.kt
class ArticleAdapter(private val itemList: ArrayList<ItemLayout>) : RecyclerView.Adapter<ArticleAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.comment_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.name.text = itemList[position].name
holder.comment.text = itemList[position].comment
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name: TextView = itemView.findViewById(R.id.list_tv_name)
val comment: TextView = itemView.findViewById(R.id.list_tv_number)
}
}
5) 해당 코드 작성
package com.example.kotlin_ot_project_i
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.view.setPadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.kotlin_ot_project_i.data.ArticleAdapter
import com.example.kotlin_ot_project_i.data.ItemLayout
import com.example.kotlin_ot_project_i.databinding.ActivityCommentBinding
import com.google.firebase.firestore.FirebaseFirestore
class CommentActivity : AppCompatActivity() {
private lateinit var binding: ActivityCommentBinding
val db = FirebaseFirestore.getInstance()
val itemList = arrayListOf<ItemLayout>()
val adapter = ArticleAdapter(itemList)
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityCommentBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
val view = binding.root
setContentView(view)
val popupMenu = PopupMenu(applicationContext,binding.creditBar.menuBtn)
menuInflater.inflate(R.menu.menu_pop_up, popupMenu.menu)
toolbarFun(binding.creditBar.menuBtn,this ,popupMenu, this, 6)
returnFun(binding.creditBar.returnBtn, this)
binding.commentRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
binding.commentRecyclerView.adapter = adapter
commentUpdate()
binding.resetButton.setOnClickListener {
commentUpdate()
}
binding.addButton.setOnClickListener {
commentAdd()
}
}
private fun commentUpdate(){
db.collection("articles")
.get()
.addOnSuccessListener { result ->
itemList.clear()
for (document in result) {
val item = ItemLayout(document["name"] as String, document["comment"] as String)
itemList.add(item)
}
adapter.notifyDataSetChanged() // recyclerVIew 갱신
}
.addOnFailureListener { exception ->
showToast(this, "불러오기 실패")
Log.w("CommentActivity", "Error for: $exception")
}
}
private fun commentAdd() {
val builder = AlertDialog.Builder(this)
val tvName = TextView(this)
tvName.text = "이름"
val tvComment = TextView(this)
tvComment.text = "내용"
val etName = EditText(this)
etName.maxLines = 1
val etComment = EditText(this)
etName.maxLines = 1
val mLayout = LinearLayout(this)
mLayout.orientation = LinearLayout.VERTICAL
mLayout.setPadding(16)
mLayout.addView(tvName)
mLayout.addView(etName)
mLayout.addView(tvComment)
mLayout.addView(etComment)
builder.setView(mLayout)
builder.setTitle("방명록 추가")
builder.setPositiveButton("추가") { _, _ ->
val data = hashMapOf(
"name" to etName.text.toString(),
"comment" to etComment.text.toString()
)
db.collection("articles")
.add(data)
.addOnSuccessListener {
Toast.makeText(this, "데이터가 추가되었습니다", Toast.LENGTH_SHORT).show()
commentUpdate()
}
.addOnFailureListener { exception ->
Log.w("CommentActivity", "Error for: $exception")
}
}
builder.setNegativeButton("취소") { _, _ ->
}
builder.show()
}
}
Firestore Database 에 추가 확인
참고
'Android Studio' 카테고리의 다른 글
Kotlin - Firebase Auth로 간단한 로그인 구현 (1) | 2024.03.08 |
---|---|
Android - FragmentContainerView와 BottomNavigation item으로 fragment넘기기 (2) | 2024.03.05 |
Firebase - Firestore Database 사용 (0) | 2024.02.29 |
Andorid - ViewPager2 사용해서 이미지 슬라이드 (0) | 2024.02.28 |
Android - AppCompatDelegate 사용해서 테마 바꾸기 (라이트모드/다크모드 / 시스템설정) (0) | 2024.02.28 |