728x90

Model을 제외하고, 

LiveData와 MVVM 패턴의 간단한 예제로 EditText로 text를 받아서 버튼을 누르면 가운데 Change Word!!를 변경하는 코드

 

예제 화면

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplicationmvvm.ViewModel.MyViewModel
import com.example.myapplicationmvvm.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private val binding : ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val viewModel : MyViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        setUpObserve()
        setUpClickListener()
    }
   //옵저빙 셋팅
   private fun setUpObserve(){
       viewModel.writeText.observe(this){
           binding.tvText.text = it
       }
   }
   //클릭 리스너 셋팅
    private fun setUpClickListener(){
        binding.btnButton.setOnClickListener {
            viewModel.getWriteText(binding.EditText.text.toString())
        }
    }
}

 

MyViewModel

class MyViewModel(private val repository: Repository = Repository()) : ViewModel() {
    //방식2
    //private val repository = Repository()
    
    private val _writeText = MutableLiveData<String>()
    val writeText: LiveData<String> get() = _writeText
    
    fun getWriteText(text: String) {
        _writeText.value = repository.getText(text)
    }
}

 

 

Repository

class Repository {
    // 일반적으로 local db나 api 데이터를 호출해온다.
    // 예제에서는 간단히 입력한Text를 호출하는 방식으로 작성함
    fun getText(text: String) = text
}

 

dependencies

    //by viewModels() 를 사용하려면 추가 
    implementation("androidx.activity:activity-ktx:1.8.2")
    implementation("androidx.fragment:fragment-ktx:1.6.2")
    
    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
    implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0")

 

 

 

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">

    <EditText
        android:id="@+id/EditText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="버튼"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/EditText" />

    <TextView
        android:id="@+id/tv_Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Word!!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

+ Recent posts