我试图做一些看似普遍的事情(f.i. here,second answer)。但是数据传输时可以放入f.i.进入一个viewmodel,android似乎并不关心我已经改变了textview的文本。这是我的代码(我更喜欢在findviewbyid上进行数据绑定):
的活动:
@Override
public void onItemSelected(String param) {
MainFragment oFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MainFragmentTag);
if(oFragment != null) {
oFragment.SetText(param);
getSupportFragmentManager()
.beginTransaction()
.replace(oBinding.mainContainer.getId(), oFragment)
.addToBackStack(null)
.commit();
}
}
接收片段:
public void SetText(String param) {
String sInput = oBinding.MyInputField.getText().toString();
oBinding.TextviewIWantToChange.setText(param);
Entry oEntry = Manager.CreateEntry(sInput, param);
viewmodel.Insert(oEntry);
}
显示旧的片段实例,传输右侧参数并且视图模型插入顺利进行。但是textview没有更新。有什么想法吗?
答案 0 :(得分:2)
使用Fragment参数传递数据并读取另一个片段getArguments
@Override
public void onItemSelected(String param) {
MainFragment oFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag(MainFragmentTag);
if(oFragment != null) {
Bundle bundle=new Bundle();
bundle.putString("param",param);
oFragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(oBinding.mainContainer.getId(), oFragment)
.addToBackStack(null)
.commit();
}
}
//在你需要的片段上调用它
public void SetText(String param) {
String sInput = oBinding.MyInputField.getText().toString();
oBinding.TextviewIWantToChange.setText(param);
Entry oEntry = Manager.CreateEntry(sInput, param);
viewmodel.Insert(oEntry);
}
在OnCreateView上调用thi methhod
final Bundle bundle = getArguments();
String param = bundle.getString("param");