Created
November 17, 2022 10:49
-
-
Save reuniware/9c1cec0fa9be8bd1ec099cdbe831be72 to your computer and use it in GitHub Desktop.
android mvvm livedata postvalue example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.myapplication | |
import android.os.Bundle | |
import androidx.fragment.app.Fragment | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.fragment.app.viewModels | |
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MutableLiveData | |
import androidx.lifecycle.Observer | |
import androidx.lifecycle.ViewModel | |
import androidx.navigation.fragment.findNavController | |
import com.example.myapplication.databinding.FragmentFirstBinding | |
/** | |
* A simple [Fragment] subclass as the default destination in the navigation. | |
*/ | |
class FirstFragment : Fragment() { | |
private val viewModel: MyViewModel by viewModels() | |
private var _binding: FragmentFirstBinding? = null | |
// This property is only valid between onCreateView and | |
// onDestroyView. | |
private val binding get() = _binding!! | |
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { | |
_binding = FragmentFirstBinding.inflate(inflater, container, false) | |
return binding.root | |
} | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
super.onViewCreated(view, savedInstanceState) | |
viewModel.monInformation.observe(viewLifecycleOwner, Observer { | |
_binding?.textviewFirst?.text = it | |
}) | |
viewModel.getInformation() | |
binding.buttonFirst.setOnClickListener { | |
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment) | |
} | |
} | |
override fun onDestroyView() { | |
super.onDestroyView() | |
_binding = null | |
} | |
} | |
class MyViewModel : ViewModel() { | |
//val monInformation: MutableLiveData<String> get() = getInformation() | |
val monInformation = MutableLiveData<String>() | |
// private fun getInformation(): MutableLiveData<String> { | |
// return MyRepository().getInformation() | |
// //monInformation.postValue("hello") | |
// } | |
fun getInformation() { | |
monInformation.postValue("hello") | |
} | |
override fun onCleared() { | |
super.onCleared() | |
// cleanup ici | |
} | |
} | |
class MyRepository { | |
fun getInformation(): MutableLiveData<String> { | |
return MutableLiveData("hello") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment