본문 바로가기
📱| Android/🔥 | Firebase

[Andoird, Kotlin] firebase sns 앱 만들기 4(게시물 불러오기)

by immgga 2022. 7. 19.

이번에 할 것은 데이터베이스에 저장된 포스트 데이터들을 불러와서 recyclerview 로 출력해 볼것이다.

 

1. recyclerview item 만들기

  • 이미지 설정

유저의 프로필을 보여줄 이미지는 Circle ImageView를 사용했다

<de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/post_user"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="28dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/post_img"
    app:layout_constraintBottom_toTopOf="@+id/post_main_img"
    app:layout_constraintStart_toStartOf="parent" />

 

포스트의 메인 사진을 보여주는 곳은 cardView를 사용해 끝을 둥글게 해주었다.

<androidx.cardview.widget.CardView
    android:id="@+id/post_main_img"
    android:layout_width="350dp"
    android:layout_height="350dp"
    android:layout_marginTop="65dp"
    app:cardCornerRadius="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <ImageView
        android:id="@+id/post_main_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/post_img" />

</androidx.cardview.widget.CardView>

 

2. recyclerview adapter 구현

var postDto: ArrayList<PostDto> = arrayListOf()     // post를 담을 arraylisy
var postUidList: ArrayList<String> = arrayListOf()  // 사용자의 uid를 담을 arraylist

init {
    fireStore.collection("posts").orderBy("timestamp").addSnapshotListener { querySnapShot, error ->
        postDto.clear()
        postUidList.clear()
        for (snapshot in querySnapShot!!) {
            val item = snapshot.toObject(PostDto::class.java)
            postDto.add(item)
            postUidList.add(snapshot.id)
        }
        notifyDataSetChanged()
    }
}

init 안에 firebase database의 데이터를 불러온 다음 for문으로 포스트의 정보를 담아주었다.

 

3. view 설정

inner class CustomViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
    val postUserText = itemView.findViewById<TextView>(R.id.post_user_text)
    val postMainImage = itemView.findViewById<ImageView>(R.id.post_main_image)
    val postExplain = itemView.findViewById<TextView>(R.id.post_str)
    val postTimeStamp = itemView.findViewById<TextView>(R.id.post_timestamp)
    val postUser = itemView.findViewById<CircleImageView>(R.id.post_user)
    val likeCount = itemView.findViewById<TextView>(R.id.like_count)
    val tag1 = itemView.findViewById<TextView>(R.id.hasi1_text)
    val tag2 = itemView.findViewById<TextView>(R.id.hasi2_text)
    val tag3 = itemView.findViewById<TextView>(R.id.hasi3_text)
    val like = itemView.findViewById<ImageView>(R.id.like)
    val bookMark = itemView.findViewById<ImageView>(R.id.bookmark)

    fun bind() {
        val pos = adapterPosition

        if (pos != RecyclerView.NO_POSITION) {
            itemView.setOnClickListener {
                itemClick?.onItemClick(itemView, postDto[pos], pos)
            }
        }
    }
}
  • recyclerview item의 뷰들을 불러온다.
  • bind 함수 안에 recyclerview 아이템 클릭 리스너를 구현한다.

 

// view 매핑
override fun onBindViewHolder(holder: MainPageFragmentRecyclerAdapter.CustomViewHolder, position: Int) {
    holder.postUserText.text = postDto[position].userId
    Glide.with(holder.itemView.context).load(postDto[position].imageUrl).centerCrop().into(holder.postMainImage)
    holder.postExplain.text = postDto[position].explain
    holder.postTimeStamp.text = postDto[position].timestamp
    holder.likeCount.text = postDto[position].favoriteCount.toString()
    Glide.with(holder.itemView.context).load(postDto[position].profileImg).centerCrop().into(holder.postUser)
    holder.tag1.text = postDto[position].tag1.toString()
    holder.tag2.text = postDto[position].tag2.toString()
    holder.tag3.text = postDto[position].tag3.toString()

	. . .
    
    holder.bind()
}

 

 

4. adapter 적용

val adapter = MainPageFragmentRecyclerAdapter()
binding = FragmentMainBinding.inflate(inflater, container, false)

binding.postRecyclerview.adapter = adapter
binding.postRecyclerview.layoutManager = LinearLayoutManager(context)

뷰 바인딩을 이용해 recyclerview를 불러와 적용시켰다.

 

5. 결과 화면

 

728x90

댓글