我只是在测试 Android 架构组件的 ViewModel 和 LiveData。我有一个带有一个 EditText 的基本 Activity 从用户那里接收一个数字,当单击“转换”按钮时,Textview 应该将结果乘以 0.87。例如,当我在 EditText 中输入 100 并单击转换按钮时,它应该给出 87 的结果。但是当我单击转换按钮时,Textview 会给出“android.arch.lifecycle.MutableLiveData@eb84a7b”的值。当我旋转屏幕时,结果变为 87。请你看看我的代码并告诉我应该在哪里修改代码,以便在我单击转换按钮时结果给出数字?
ViewModelLiveDataActivity.java:
public class ViewModelLiveDataActivity extends AppCompatActivity {
private ViewModel2 mViewModel;
private EditText mEditText;
private TextView mTextView;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewmodellivedata_activity_layout);
mViewModel = ViewModelProviders.of(this).get(ViewModel2.class);
mEditText = (EditText) findViewById(R.id.livedata_editText);
mTextView = (TextView) findViewById(R.id.livedata_textView);
mButton = (Button) findViewById(R.id.livedata_button);
final Observer<Float> resultObserver = new Observer<Float>() {
@Override
public void onChanged(@Nullable final Float result) {
mTextView.setText(result.toString());
}
};
mViewModel.getResult().observe(this, resultObserver);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Doing the calculations using ViewModel class
String dollarText = mEditText.getText().toString();
mViewModel.setAmount(dollarText);
mTextView.setText(mViewModel.getResult().toString());
}
});
}
}
ViewModel2.java:
public class ViewModel2 extends ViewModel {
private static final float EURO_DOLLAR_EXCHANGE_RATE = 0.87f;
private String dollarString = ""; //the value of UI EditText
private MutableLiveData<Float> result = new MutableLiveData<>();
public void setAmount(String value) {
this.dollarString = value;
result.setValue(Float.valueOf(dollarString) * EURO_DOLLAR_EXCHANGE_RATE);
}
public MutableLiveData<Float> getResult() {
return result;
}
}