要实现Android MVVM架构中的UI控件,可以按照以下步骤进行:
public class MyViewModel extends ViewModel {
private MutableLiveData text = new MutableLiveData<>();
public LiveData getText() {
return text;
}
public void setText(String newText) {
text.setValue(newText);
}
}
public class MainActivity extends AppCompatActivity {
private MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
TextView textView = findViewById(R.id.text_view);
viewModel.getText().observe(this, new Observer() {
@Override
public void onChanged(String newText) {
textView.setText(newText);
}
});
}
}
public class MainActivity extends AppCompatActivity {
private MyViewModel viewModel;
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MyViewModel.class);
binding.setViewModel(viewModel);
}
}
通过上述步骤,你就可以实现Android MVVM架构中的UI控件,并将其与ViewModel中的数据和状态绑定在一起。在ViewModel中更新数据时,UI控件会自动更新。