您可以使用范围为activity生命周期的共享ViewModel,并使用它在片段之间共享数据。
来自文档的代码:
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}
更多信息请参见:https://developer.android.com/topic/libraries/architecture/ViewModel#Sharing
简单地说,您可以使用bundle将数据从一个片段传递到另一个片段,就像这样
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment2 fragment2 = new Fragment2();
Bundle bundle = new Bundle();
msubcategories.setArguments(bundle);
bundle.putString("data", data);
fragmentTransaction.replace(R.id.fragment_container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
在Fragment2中,您可以获得数据
Bundle bundle = getArguments();
assert bundle != null;
String category = bundle.getString("data");