多个fragment内实现ViewModel的共享
时间: 2024-05-01 20:16:38 浏览: 191
在多个Fragment之间共享ViewModel,可以使用以下步骤:
1. 创建一个ViewModel类,该类包含需要共享的数据和方法。
```java
public class SharedViewModel extends ViewModel {
private MutableLiveData<String> selected = new MutableLiveData<String>();
public void select(String item) {
selected.setValue(item);
}
public LiveData<String> getSelected() {
return selected;
}
}
```
2. 在需要共享ViewModel的Fragment中,通过ViewModelProvider获取ViewModel实例。
```java
public class Fragment1 extends Fragment {
private SharedViewModel model;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
}
// ...
}
```
3. 在其他需要访问ViewModel的Fragment中,也通过ViewModelProvider获取同一个ViewModel实例。
```java
public class Fragment2 extends Fragment {
private SharedViewModel model;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
}
// ...
}
```
4. 在Fragment中使用ViewModel中的数据和方法。这样就可以在多个Fragment之间共享ViewModel了。
```java
public class Fragment1 extends Fragment {
private SharedViewModel model;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button button = view.findViewById(R.id.button);
final EditText editText = view.findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
model.select(editText.getText().toString());
}
});
return view;
}
}
public class Fragment2 extends Fragment {
private SharedViewModel model;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
final TextView textView = view.findViewById(R.id.textView);
model.getSelected().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(String item) {
textView.setText(item);
}
});
return view;
}
}
```
阅读全文