Android 공부/Android AAC

MVVM : RecyclerView, LiveData

Machine_웅 2022. 3. 28. 14:18
728x90
반응형

Main Fragment

class Main_fragment : Fragment(), BoardInter {

    val SCREEN_ADMIN = 1
    val SCREEN_MYQ = 2
    val SCREEN_BOARD = 3 //  override fun click(data: BoardData)
    val SCREEN_FRIENDMAIN = 4

    lateinit var txt_myPoint: TextView
    lateinit var binding: FragmentMainFragmentBinding

    // MVVM
    lateinit var viewModel: Vm_Main
    lateinit var adapter: Adapter_MainBoard;


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLog().d("onCreate")
        // mLog().d("MSingleTon : " + MSingleTon.userData.toString())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_main_fragment, container, false)
        binding.fragment = this

        // 뷰모델 세팅
        viewModel = ViewModelProvider(this).get(Vm_Main::class.java)

        // 뷰모델에 Live 데이터를 옵져빙해서 변경시 값을 리싸이클러뷰에 반영한다.
        viewModel.getAll().observe(this, Observer { contacts ->
            if (contacts.size > 0) {
                if (::adapter.isInitialized) {
                    mLog().d("갱신")
                    adapter.notifyDataSetChanged()
                } else {
                    mLog().d("초기화")
                    binding.recyclerViewBoard.also {
                        it.layoutManager =
                            GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false)
                        adapter = Adapter_MainBoard(this, viewModel.backImage, contacts)
                        it.adapter = adapter
                    }
                }
            } else {
                // No Data
            }
        })
        binding.viewModel = viewModel

        // setAdapter()
        return binding.root
    }

    // list item 이벤트
    override fun click(data: BoardData) {
        val bundle = bundleOf("clickData" to data)
        findNavController().navigate(R.id.action_main_to_questBoardMain, bundle)
    }

    fun gotoPage(screen: Int) {
        when (screen) {
            SCREEN_ADMIN -> {
                viewModel.changeData()
            }
            SCREEN_MYQ -> {
                viewModel.changeData2()
            }
            SCREEN_FRIENDMAIN -> {
                findNavController().navigate(R.id.action_maint_to_friend)
            }
            else -> {

            }
        }
    }


    // api call back
    private val api_callback_coroutine = (object : API_coroutines.CallbackInter {
        override fun cResult(result: JSONObject?) {
            mLog().d("" + result.toString())
            txt_myPoint.text = result.toString()
        }
    })


}

 

 

xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="fragment"
            type="kr.appgrider.mvpGame.Main_fragment" />

        <variable
            name="viewModel"
            type="kr.appgrider.mvpGame.Vm_Main" />
    </data>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/tilebackground"
        android:orientation="vertical"
        tools:context="kr.appgrider.mvpGame.Main_fragment">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="navigation" />
        <!--  Top point  -->

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:orientation="horizontal"
            android:paddingHorizontal="10dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/woodborder" />

            <androidx.appcompat.widget.LinearLayoutCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="보유 Point"
                    android:textColor="#fff"
                    android:textSize="20dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/txt_myPoint"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingHorizontal="10dp"
                    android:text="100,000"
                    android:textColor="#fff"
                    android:textSize="20dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="p"
                    android:textColor="#fff"
                    android:textSize="20dp"
                    android:textStyle="bold" />

            </androidx.appcompat.widget.LinearLayoutCompat>


        </FrameLayout>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_friend"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="right"
            android:visibility="gone"
            android:text="친구"
            android:onClick="@{()->fragment.gotoPage(4)}"
            />


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView_Board"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="140dp"
            android:orientation="vertical">


            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp">

                <ImageButton
                    android:id="@+id/btn_adminQ"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:background="#00ffffff"
                    android:scaleType="centerCrop"
                    android:src="@drawable/woodborder"
                    android:onClick="@{()->fragment.gotoPage(1)}"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:clickable="false"
                    android:textSize="20dp"
                    android:text="퀘스트 관리"
                    android:textColor="#fff" />

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <ImageButton
                    android:id="@+id/btn_myQ"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:background="#00ffffff"
                    android:scaleType="centerCrop"
                    android:src="@drawable/woodborder"
                    android:text="나의 퀘스트"
                    android:onClick="@{()->fragment.gotoPage(2)}"
                    />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:clickable="false"
                    android:text="나의 퀘스트"
                    android:textSize="20dp"
                    android:textColor="#fff" />

            </FrameLayout>


        </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.appcompat.widget.LinearLayoutCompat>
</layout>

 

ViewModel

package kr.appgrider.mvpGame

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import kr.appgrider.game.R
import kr.appgrider.mvpGame.model.BoardData
import kr.appgrider.util.mLog

class Vm_Main(application: Application) : AndroidViewModel(application){

    // 라이브데이터로 관찰할 데이터
    var boardArray : MutableLiveData<MutableList<BoardData>> = MutableLiveData<MutableList<BoardData>>()

    var backImage : ArrayList<Int>  = ArrayList()

    init {
        initImageArr()
        setBoardData()
    }

    fun getAll() : MutableLiveData<MutableList<BoardData>>  {
        return this.boardArray
    }

    fun initImageArr() {
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
        backImage.add(R.drawable.house05)
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
        backImage.add(R.drawable.house05)
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
        backImage.add(R.drawable.house05)
        backImage.add(R.drawable.house01)
        backImage.add(R.drawable.house02)
        backImage.add(R.drawable.house03)
        backImage.add(R.drawable.house04)
    }
    fun setBoardData() {
        var dataArr : MutableList<BoardData> = mutableListOf()
        dataArr.add(BoardData("테스트1", "Board01", "", false))
        dataArr.add(BoardData("테스트2", "Board02", "", false))
        dataArr.add(BoardData("테스트3", "Board03", "", true))
        dataArr.add(BoardData("테스트4", "Board04", "", false))
        boardArray.postValue(dataArr)
    }

    fun changeData(){
        mLog().d("클릭")
        var tmp : MutableList<BoardData> ? = this.boardArray.value
        tmp!!.get(0).BoardNew = true
        this.boardArray.value = tmp
    }

    fun changeData2(){
        mLog().d("클릭")
        var tmp : MutableList<BoardData> ? = this.boardArray.value
        tmp!!.add(BoardData("테스트3", "Board03", "", true))
        tmp!!.add(BoardData("테스트4", "Board04", "", false))
        this.boardArray.value = tmp
    }

}

 

adapter

class Adapter_MainBoard(
    val inter: BoardInter,
    val backImgArr: ArrayList<Int>,
    var data: MutableList<BoardData>
): RecyclerView.Adapter<Adapter_MainBoard.DViewHolder>() {

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): DViewHolder {
        val binding: ItemBoardBinding =
            ItemBoardBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)
        return DViewHolder(binding)
    }
    override fun onBindViewHolder(holder: DViewHolder, position: Int) {
        holder.onBind(data.get(position), backImgArr.get(position), inter)
    }
    override fun getItemCount(): Int { return data.size}

    // 데이터 바인딩 뷰홀더
    class DViewHolder(val binding: ItemBoardBinding) : RecyclerView.ViewHolder(binding.root) {
        fun onBind(data: BoardData, imageRes: Int, inter: BoardInter) {
            // 데이터 입력
            binding.itemTxtTitle.text = data.BoardName
            binding.itemLayout.setBackgroundResource(imageRes)
            binding.itemLayout.setOnClickListener { inter.click(data) }
            if (data.BoardNew) {
                binding.itemNewNoti.visibility = View.VISIBLE
            } else {
                binding.itemNewNoti.visibility = View.GONE
            }
        }
    }
}
728x90
반응형

'Android 공부 > Android AAC' 카테고리의 다른 글

DATA_Binding : RecyclerView in fragment  (0) 2022.03.11
DATA_Binding : Fragment  (0) 2022.03.10
MVVM LiveData (1)  (0) 2021.02.22
Android AAC : LiveData  (0) 2021.01.07
Android ACC : Data Binding  (0) 2021.01.06