0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【kotlin】超簡単なMVVMを実装してみた、①ViewModelの実装

Last updated at Posted at 2023-09-08

MVVMとは?

Androidアーキテクチャの一つ。
ActivityやFragmentで行っていた処理を以下の三つの役割に分ける。

・Model(データに関する処理を行う)
・View(画面に関する処理、クリック等のイベントを拾ってViewとModelに送る処理を行う)
・ViewModel(ViewとModel間で、情報を加工・伝達する処理を行う)

実装内容

EditTextに文字を入力してボタンを押したら、下部のTextViewに表示させる(超簡単)。
Screenshot_20230908_183356.png

下記のURLと同じ動作です。
https://qiita.com/Na0yaKub0/items/d688c440dfa9c3a49a7f

実装

・ViewModelの設定

class MainViewModel : ViewModel(){

    private val _textViewStr: MutableLiveData<String> by lazy { MutableLiveData<String>("")}
    val textViewStr: LiveData<String> = _textViewStr

    // ボタンをクリックしたときの処理
    fun onClickButton(text: String) {
        _textViewStr.value = text
    }
}

・View設定

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // viewBinding初期化
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        // viewModel初期化
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]

        binding.button.setOnClickListener {
            viewModel.onClickButton(binding.editTextText.text.toString())
        }

        //  LiveDataを読み込み反映
        viewModel.textViewStr.observe(this, Observer {
            binding.textView.text = it
        })
    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?