Activity에 포함된 둘 이상의 프래그먼트는 ViewModel을 통해서 데이터 공유가 가능합니다.
위 그림과 같이 Fragment들은 각자의 ViewModel를 가질 수도 있고 Activity의 ViewModel을 공유해서 사용할 수도 있는 것 입니다.
1. Fragment1
class Fragment1 : Fragment() {
private val sharedViewModel: SharedViewModel by activityViewModels()
private lateinit var binding: Fragment1Binding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = Fragment1Binding.inflate(inflater, container, false)
binding.buttonFragment1.setOnClickListener {
sharedViewModel.updateText(binding.editTextFromFragment1.text as Editable)
}
sharedViewModel.getData().observe(viewLifecycleOwner, Observer {
binding.editTextFromFragment1.text = it as Editable
})
return binding.root
}
}
sharedViewModel.getData().observe()를 통해서 ViewModel에 선언된 MutableLiveData의 data 값이 변하는지 관찰합니다. 이러한 옵저빙을 통해서 데이터 변환이 감지되면 text값을 갱신해 줍니다.
2. Fragment2
class Fragment2 : Fragment() {
private lateinit var binding: Fragment2Binding
private val sharedViewModel: SharedViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = Fragment2Binding.inflate(inflater, container, false)
binding.buttonFragment2.setOnClickListener {
sharedViewModel.updateText(binding.editTextFromFragment2.text as Editable)
}
sharedViewModel.getData().observe(viewLifecycleOwner, Observer {
binding.editTextFromFragment2.text = it as Editable
})
return binding.root
}
}
3. SharedViewModel
class SharedViewModel : ViewModel() {
private var inputText: MutableLiveData<CharSequence> = MutableLiveData()
fun getData(): MutableLiveData<CharSequence> = inputText
fun updateText(input: CharSequence) {
inputText.value = input
}
}
4. MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.apply {
add(R.id.fragment_1_holder, Fragment1())
add(R.id.fragment_2_holder, Fragment2())
commit()
}
}
}
https://www.geeksforgeeks.org/fragment-to-fragment-communication-in-android-using-shared-viewmodel/