我具有以下设置:
- 持有 MainFragment 的单个 Mainactivity
- Mainactivity 具有用于存储整数列表的ViewModel
- Mainactivity 在此ViewModel中写入整数值
- 我想在 MainFragment 中打印这些值
- 我能够访问ViewModel实例,但无法从该实例获取List值
Mainactivity :
public class Mainactivity extends AppCompatactivity {
private MainViewModel mViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
// Adding integer values in ViewModel
mViewModel.selectInteger(1);
mViewModel.selectInteger(10);
mViewModel.selectInteger(111);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container,MainFragment.newInstance())
.commitNow();
}
}
}
MainFragment :
public class MainFragment extends Fragment {
private MainViewModel mViewModel;
private TextView tv;
public static MainFragment newInstance() {
return new MainFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment,container,false);
tv = rootView.findViewById(R.id.myTextView);
return rootView;
}
@Override
public void onactivityCreated(@Nullable Bundle savedInstanceState) {
super.onactivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getactivity()).get(MainViewModel.class);
// I am getting error in below line,Not able to pass List of integer to formatList function
mViewModel.getListOfInt().observe(getactivity(),{value -> {formatList(value)}});
}
private String formatList(List<Integer> list) {
String returnValue = "";
for(Integer a : list) {
returnValue = returnValue + a;
}
return returnValue;
}
}
MainViewModel :
public class MainViewModel extends ViewModel {
// TODO: Implement the ViewModel
private final MutableLiveData<List<Integer>> listOfInt = new MutableLiveData<List<Integer>>();
public MutableLiveData<List<Integer>> getListOfInt() {
return listOfInt;
}
public void selectInteger(Integer a) {
List<Integer> current = listOfInt.getvalue();
current.add(a);
listOfInt.setvalue(current);
}
}
将整数列表传递给formatList()
方法时出现错误。