티스토리 뷰
MVVM + Room + RecyclerView + CardView + AlertDialog
build.gradle (Module: app)
apply plugin: 'kotlin-kapt'
dependencies {
// RecyclerView
implementation 'androidx.recyclerview:recyclerview:1.1.0'
// CardView
implementation 'androidx.cardview:cardview:1.0.0'
// Room
implementation 'androidx.room:room-runtime:2.2.5'
kapt 'androidx.room:room-compiler:2.2.5'
testImplementation 'androidx.room:room-testing:2.2.5'
}
UserEntity.kt
package com.jwsoft.kotlinproject
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "user")
data class UserEntity (
@PrimaryKey(autoGenerate = true) var id: Long?,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "phone") var phone: String,
@ColumnInfo(name = "age") var age: Int
) {
constructor() : this(null, "", "", 0)
}
UserDao.kt
package com.jwsoft.kotlinproject
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: UserEntity)
@Query("SELECT * FROM user ORDER BY age ASC")
fun getAll(): LiveData<List<UserEntity>>
@Query("DELETE FROM user")
fun deleteAll()
@Delete
fun delete(user: UserEntity)
}
UserDB.kt
package com.jwsoft.kotlinproject
import android.app.Application
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [UserEntity::class], version = 1)
abstract class UserDB : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
var INSTANCE: UserDB? = null
fun getInstance(context: Context): UserDB {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context, UserDB::class.java, "MyApp.db")
.fallbackToDestructiveMigration()
.build()
}
return INSTANCE!!
}
}
}
UserRepository.kt
package com.jwsoft.kotlinproject
import android.app.Application
import androidx.lifecycle.LiveData
class UserRepository(application: Application) {
private val userDB: UserDB = UserDB.getInstance(application)
private val userDao: UserDao = userDB.userDao()
var getAll: LiveData<List<UserEntity>> = userDao.getAll()
fun insert(userEntity: UserEntity) {
try {
Thread {
userDao.insert(userEntity)
}.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun getAll(): LiveData<List<UserEntity>> {
return getAll
}
fun deleteAll() {
try {
Thread {
userDao.deleteAll()
}.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun delete(userEntity: UserEntity) {
try {
Thread {
userDao.delete(userEntity)
}.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
UserViewModel.kt
package com.jwsoft.kotlinproject
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
class UserViewModel(application: Application) : AndroidViewModel(application) {
val userRepository: UserRepository = UserRepository(application)
var getAll: LiveData<List<UserEntity>> = userRepository.getAll()
fun insert(userEntity: UserEntity) {
userRepository.insert(userEntity)
}
fun getAll(): LiveData<List<UserEntity>> {
return getAll
}
fun deleteAll() {
userRepository.deleteAll()
}
fun delete(userEntity: UserEntity) {
userRepository.delete(userEntity)
}
}
cardview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="10dp"
android:elevation="10dp"
app:cardCornerRadius="5dp">
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCCCCC"/>
<TextView
android:id="@+id/tvAge"
android:layout_width="80dp"
android:layout_height="80dp"
android:elevation="10dp"
android:hint="30"
android:textSize="36dp"
android:textStyle="bold"
android:gravity="center"
android:background="#BBBBBB"
android:layout_marginLeft="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
app:layout_constraintLeft_toRightOf="@+id/tvAge"
app:layout_constraintRight_toRightOf="parent">
<TextView
android:id="@+id/tvName"
android:hint="James Kim"
android:textSize="30dp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvPhone"
android:hint="010-1234-5678"
android:textSize="18dp"
android:textStyle="italic"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
MyAdapter.kt
package com.jwsoft.kotlinproject
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MyAdapter(clickListener: OnItemClickListener,
longClickListener: OnItemLongClickListener
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
var users: List<UserEntity> = listOf()
interface OnItemClickListener {
fun onClick(user: UserEntity)
}
interface OnItemLongClickListener {
fun onLongClick(user: UserEntity)
}
var clickListener: OnItemClickListener = clickListener
var longClickListener: OnItemLongClickListener = longClickListener
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
lateinit var tvName: TextView
lateinit var tvPhone: TextView
lateinit var tvAge: TextView
fun bind(user: UserEntity) {
tvName = itemView.findViewById(R.id.tvName)
tvPhone = itemView.findViewById(R.id.tvPhone)
tvAge = itemView.findViewById(R.id.tvAge)
tvName.text = user.name
tvPhone.text = user.phone
tvAge.text = user.age.toString()
itemView.setOnClickListener {
clickListener.onClick(user)
}
itemView.setOnLongClickListener {
longClickListener.onLongClick(user)
true
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val context = parent.context
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.cardview_item, parent, false)
return MyViewHolder(view)
}
override fun getItemCount(): Int {
if (users == null || users.isEmpty()) {
return 0
}
return users.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(users[position])
}
fun setAdapter(user: List<UserEntity>) {
this.users = user
notifyDataSetChanged()
}
}
activity_main.xml
<?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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rvUser"
android:layout_width="match_parent"
android:layout_height="0dp"
tools:listitem="@layout/cardview_item"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@+id/btnAdd"/>
<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textAllCaps="false"
android:text="Add"
android:textSize="30dp"
android:textStyle="bold"
android:layout_margin="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.jwsoft.kotlinproject
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var userViewModel: UserViewModel
lateinit var adapter: MyAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val clickListener = object: MyAdapter.OnItemClickListener {
override fun onClick(user: UserEntity) {
var intent: Intent = Intent(this@MainActivity, AddActivity::class.java)
intent.putExtra("id", user.id)
intent.putExtra("name", user.name)
intent.putExtra("phone", user.phone)
intent.putExtra("age", user.age)
startActivity(intent)
finish()
}
}
val longClickListener = object: MyAdapter.OnItemLongClickListener {
override fun onLongClick(user: UserEntity) {
showAlertDialog(user)
}
}
adapter = MyAdapter(clickListener, longClickListener)
rvUser.adapter = adapter
rvUser.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
rvUser.setHasFixedSize(true)
userViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(UserViewModel::class.java)
userViewModel.getAll().observe(this, object: Observer<List<UserEntity>> {
override fun onChanged(t: List<UserEntity>?) {
if (t != null) {
adapter.setAdapter(t)
}
}
})
btnAdd.setOnClickListener {
startActivity(Intent(this, AddActivity::class.java))
}
}
fun showAlertDialog(user: UserEntity) {
var alertDialog: AlertDialog = AlertDialog.Builder(this)
.setTitle("Delete")
.setMessage("Do you want to delete user?")
.setPositiveButton("OK", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
userViewModel.delete(user)
}
})
.setNegativeButton("Cancel", object: DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
Toast.makeText(applicationContext, "Cancel", Toast.LENGTH_SHORT).show()
}
})
.create()
alertDialog.show()
}
}
activity_add.xml
<?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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="24dp"
android:layout_marginLeft="20dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/btnDone"
app:layout_constraintLeft_toLeftOf="parent" />
<TextView
android:id="@+id/tvPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:textSize="24dp"
android:layout_marginTop="30dp"
app:layout_constraintLeft_toLeftOf="@+id/tvName"
app:layout_constraintTop_toBottomOf="@+id/tvName"/>
<TextView
android:id="@+id/tvAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="24dp"
android:layout_marginTop="30dp"
app:layout_constraintLeft_toLeftOf="@+id/tvName"
app:layout_constraintTop_toBottomOf="@+id/tvPhone"/>
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="12"
android:layout_marginLeft="30dp"
app:layout_constraintStart_toEndOf="@+id/tvName"
app:layout_constraintTop_toTopOf="@+id/tvName"
app:layout_constraintBottom_toBottomOf="@+id/tvName" />
<EditText
android:id="@+id/etPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="12"
android:inputType="phone"
app:layout_constraintTop_toTopOf="@+id/tvPhone"
app:layout_constraintBottom_toBottomOf="@+id/tvPhone"
app:layout_constraintStart_toStartOf="@+id/etName" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="12"
app:layout_constraintTop_toTopOf="@+id/tvAge"
app:layout_constraintBottom_toBottomOf="@+id/tvAge"
app:layout_constraintStart_toStartOf="@+id/etPhone" />
<Button
android:id="@+id/btnDone"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textAllCaps="false"
android:text="Done"
android:textSize="26dp"
android:textStyle="bold"
android:layout_margin="4dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
AddActivity.kt
package com.jwsoft.kotlinproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import kotlinx.android.synthetic.main.activity_add.*
class AddActivity : AppCompatActivity() {
lateinit var userViewModel: UserViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
userViewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(UserViewModel::class.java)
etName.setText(intent.getStringExtra("name"))
etPhone.setText(intent.getStringExtra("phone"))
etAge.setText(intent.getIntExtra("age", 0).toString())
btnDone.setOnClickListener {
var user = UserEntity()
user.name = etName.text.toString()
user.phone = etPhone.text.toString()
user.age = Integer.parseInt(etAge.text.toString())
if (intent.getLongExtra("id", 0) > 0) {
user.id = intent.getLongExtra("id", 0)
}
userViewModel.insert(user)
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
}
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] Generics (0) | 2020.07.27 |
---|---|
[Kotlin] Coroutine (1) (0) | 2020.07.23 |
[Kotlin] RecyclerView + ItemClickListener + ItemLongClickListener (0) | 2020.07.21 |
[Kotlin] AlertDialog (0) | 2020.07.21 |
[Kotlin] Room (0) | 2020.07.21 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Vue.js #Vue.js + javascript
- 안드로이드 #코틀린 #Android #Kotlin
- TabLayout
- James Kim
- Kotlin
- Architecture Pattern
- java
- coroutine
- 혀가 길지 않은 개발자
- 자바
- ArrayList
- Design Pattern
- DataBinding
- ViewModel
- View
- JSONObject
- Livedata
- 안드로이드
- Intent
- ViewPager2
- CoordinatorLayout
- activity
- 코틀린
- recyclerview
- MVVM
- handler
- Android
- JSONArray
- fragment
- XML
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함