android mvvm模板代码
时间: 2023-08-08 11:08:06 浏览: 130
以下是一个简单的Android MVVM模板代码:
Model类:
```java
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
```
ViewModel类:
```java
public class UserViewModel extends ViewModel {
private MutableLiveData<User> userLiveData;
public LiveData<User> getUserLiveData() {
if (userLiveData == null) {
userLiveData = new MutableLiveData<>();
loadUser();
}
return userLiveData;
}
private void loadUser() {
// 从网络或数据库中获取User信息
User user = new User("Tom", "tom@example.com");
userLiveData.setValue(user);
}
}
```
View类:
```java
public class MainActivity extends AppCompatActivity {
private TextView nameTextView;
private TextView emailTextView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTextView = findViewById(R.id.nameTextView);
emailTextView = findViewById(R.id.emailTextView);
progressBar = findViewById(R.id.progressBar);
UserViewModel userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
userViewModel.getUserLiveData().observe(this, user -> {
// 更新UI显示
nameTextView.setText(user.getName());
emailTextView.setText(user.getEmail());
progressBar.setVisibility(View.GONE);
});
}
}
```
此模板代码展示了一个简单的MVVM架构,其中Model类为User,ViewModel类为UserViewModel,View类为MainActivity。通过ViewModel的getUserLiveData()方法获取LiveData对象,当数据更新时,LiveData会自动通知View更新UI显示。
阅读全文