Android Jetpack

ROOM + FLOW CRUD - 3

----___<<<<< 2022. 7. 12. 03:47

 

 recyclerView를 붙여서 ROOM FLOW와 결합해보겠습니다.

 

// viewModelScope
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
class CustomAdapter : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    private val TAG = CustomAdapter::class.java.simpleName

    private var textList = ArrayList<TextEntity>()

    class ViewHolder(view : View) : RecyclerView.ViewHolder(view){

        val textView : TextView = view.findViewById(R.id.textArea)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.text_row_item, parent, false)

        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.textView.text = textList[position].text

        holder.itemView.setOnClickListener {
            Log.d(TAG, textList[position].toString())
        }
    }

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

    fun setData(text_list : ArrayList<TextEntity>){
        textList = text_list
        notifyDataSetChanged()
    }
}
class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MainViewModel
    private val customAdapter : CustomAdapter by lazy {
        CustomAdapter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        val insertBtn = findViewById<Button>(R.id.insertBtn)
        val rv = findViewById<RecyclerView>(R.id.rv)

        insertBtn.setOnClickListener {

            // Dialog만들기
            val mDialogView = LayoutInflater.from(this).inflate(R.layout.custom_dialog, null)
            val mBuilder = AlertDialog.Builder(this)
                .setView(mDialogView)
                .setTitle("Login Form")

            val mAlertDialog = mBuilder.show()

            val okButton = mDialogView.findViewById<Button>(R.id.successButton)
            val inputText = mDialogView.findViewById<EditText>(R.id.editText)

            okButton.setOnClickListener {

                viewModel.insert(inputText.text.toString())

                mAlertDialog.dismiss()

            }

        }

        viewModel.readAllData.observe(this, Observer {

            customAdapter.setData(it as ArrayList<TextEntity>)

        })
        rv.adapter = customAdapter
        rv.layoutManager = LinearLayoutManager(this)

    }

}

 

 

 

'Android Jetpack' 카테고리의 다른 글

ROOM Migration  (0) 2022.07.22
ROOM + FLOW CRUD - 4 (DELTE, UPDATE)  (0) 2022.07.17
ROOM + FLOW CRUD - 2  (0) 2022.07.11
ROOM + FLOW CRUD - 1  (0) 2022.07.03
ROOM + FLOW  (0) 2022.06.27