android mvvm框架搭建请给我写一份代码
时间: 2024-05-06 16:19:16 浏览: 94
好的,以下是一个基于Android MVVM框架搭建的简单示例代码:
Model层(数据源):
```
public class UserRepository {
private UserApi userApi;
public UserRepository() {
userApi = RetrofitClient.getInstance().create(UserApi.class);
}
public LiveData<User> getUser(String userId) {
final MutableLiveData<User> data = new MutableLiveData<>();
userApi.getUser(userId).enqueue(new Callback<UserResponse>() {
@Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
data.setValue(response.body().getData());
}
}
@Override
public void onFailure(Call<UserResponse> call, Throwable t) {
data.setValue(null);
}
});
return data;
}
}
```
ViewModel层(数据处理):
```
public class UserViewModel extends ViewModel {
private UserRepository userRepository;
private MutableLiveData<User> userLiveData = new MutableLiveData<>();
public UserViewModel() {
userRepository = new UserRepository();
}
public LiveData<User> getUser(String userId) {
userLiveData = userRepository.getUser(userId);
return userLiveData;
}
}
```
View层(界面展示):
```
public class UserActivity extends AppCompatActivity {
private UserViewModel userViewModel;
private TextView tvUserId;
private TextView tvUserName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
tvUserId = findViewById(R.id.tv_user_id);
tvUserName = findViewById(R.id.tv_user_name);
String userId = getIntent().getStringExtra("userId");
userViewModel.getUser(userId).observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
if (user != null) {
tvUserId.setText(user.getId());
tvUserName.setText(user.getName());
} else {
Toast.makeText(UserActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}
```
以上代码实现了从后台获取User对象并展示到界面上的功能,具体使用时可以根据实际需求调整。
阅读全文