利用viewmodel进行activity与fragment之间传值
本人毕业设计选的是基于android开发一个平台,但我的专业并不是学习开发android,所以也算是从头学起(小白),写这个只是为了记录自己开发过程的一些小难题(大难题我也是请教大佬)。
开始
首先利用android studio创建一个自带的底部导航栏
运行效果就是
在activity中传输数据到fragment中
主要是通过viewmodel(android小白的话可以去了解一下MVVM),以Dashboard为例;
在DashFragment的onCreateView方法里面
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(getActivity()).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
TextView textView = root.findViewById(R.id.text_dashboard);
textView.setText(dashboardViewModel.getText().getValue());
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}`
注意的是dashboardViewModel =new ViewModelProvider(getActivity()).get(DashboardViewModel.class),初始的时候填写的是this。再到Mainactivity中
viewModel=new ViewModelProvider(this).get(DashboardViewModel.class);
viewModel.mText.setValue("nid");
还有一点在DashboardViewmodel中修改了一些东西
public class DashboardViewModel extends ViewModel {
public MutableLiveData<String> mText= new MutableLiveData<>();;
public DashboardViewModel() {
}
public void setText(String s)
{
mText.setValue(s);
}
public LiveData<String> getText() {
return mText;
}
}
最后效果
第一次进行创作,继续努力。。。