Base层框架同Day2创建FoodEntity、Api接口、RetrifitManager管理类
Api接口:
package com.bw.day3.MVVM.Base.Http;
import com.bw.day3.MVVM.Base.Entity.FoodEntity;
import com.bw.day3.MVVM.Base.Entity.UserEntity;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface Api {
@GET("foods/getFoods")
Observable<FoodEntity> getFoodData(@Query("currentPage") int currentPage, @Query("pageSize")int pageSize);
@POST("user/register")
Observable<UserEntity> postRegisterData(@Body RequestBody body);
@POST("user/loginjson")
Observable<UserEntity> postLoginData(@Body RequestBody body);
}
在Model创建BaseModel
package com.bw.day3.MVVM.Base.Model;
import com.bw.day3.MVVM.Base.Http.Api;
import com.bw.day3.MVVM.Base.Http.RetrifitManager;
public class BaseModel {
protected Api api;
public BaseModel() {
api= RetrifitManager.getInstance().creatrRetrofit().create(Api.class);
}
}
在ViewModel包中创建BaseViewModel:
package com.bw.day3.MVVM.Base.ViewModel;
import androidx.lifecycle.ViewModel;
import com.bw.day3.MVVM.Base.Model.BaseModel;
public abstract class BaseViewModel <BaMo extends BaseModel>extends ViewModel {
protected BaMo bModel;
public BaseViewModel() {
bModel=creatModel();
}
protected abstract BaMo creatModel();
}
创建BaseActivity:
package com.bw.day3.MVVM.Base.View;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProvider;
import com.bw.day3.MVVM.Base.ViewModel.BaseViewModel;
public abstract class BaseActivity <VDB extends ViewDataBinding ,VM extends BaseViewModel>extends AppCompatActivity {
protected VDB viewDataBinding;
protected VM viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewDataBinding= DataBindingUtil.setContentView(this, getLayoutid());
viewModel=new ViewModelProvider(this).get(getViewModel());
initView();
initData();
handObserver();
}
protected abstract Class<VM> getViewModel();
protected abstract int getLayoutid();
protected abstract void initView();
protected abstract void initData();
protected void handObserver() {
}
}
Food应用层创建Food包:
创建FoodModel继承BaseModel:
package com.bw.day3.MVVM.Food;
import com.bw.day3.MVVM.Base.Entity.FoodEntity;
import com.bw.day3.MVVM.Base.Model.BaseModel;
import io.reactivex.Observable;
public class FoodModel extends BaseModel {
public Observable<FoodEntity> getFoodData(int currentPage,int pageSize){
return api.getFoodData(currentPage,pageSize);
}
}
创建FoodViewModel继承BaseViewModel泛型为FoodModel:
package com.bw.day3.MVVM.Food;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.bw.day3.MVVM.Base.Entity.FoodEntity;
import com.bw.day3.MVVM.Base.ViewModel.BaseViewModel;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class FoodViewModel extends BaseViewModel<FoodModel> {
public MutableLiveData<FoodEntity> liveData=new MutableLiveData<>();
@Override
protected FoodModel creatModel() {
return new FoodModel();
}
public void getFood(int page,int size){
bModel.getFoodData(page,size)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<FoodEntity>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(FoodEntity foodEntity) {
Log.i("TAG", "onNext: "+foodEntity.getData().size());
liveData.postValue(foodEntity);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
创建FoodActivity继承BaseActivity泛型为ActivityFoodBinding,FoodViewModel:
package com.bw.day3.MVVM.Food;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.bw.day3.MVVM.Base.Adapter.FoodAdapter;
import com.bw.day3.MVVM.Base.Entity.FoodEntity;
import com.bw.day3.MVVM.Base.View.BaseActivity;
import com.bw.day3.R;
import com.bw.day3.databinding.ActivityFoodBinding;
import java.util.ArrayList;
import java.util.List;
public class FoodActivity extends BaseActivity<ActivityFoodBinding,FoodViewModel> {
protected List<FoodEntity.DataBean> list=new ArrayList<>();
protected FoodAdapter adapter;
@Override
protected Class<FoodViewModel> getViewModel() {
return FoodViewModel.class;
}
@Override
protected int getLayoutid() {
return R.layout.activity_food;
}
@Override
protected void initView() {
viewModel.getFood(1,10);
}
@Override
protected void initData() {
viewDataBinding.rv.setLayoutManager(new LinearLayoutManager(FoodActivity.this));
viewDataBinding.rv.setAdapter(adapter);;
}
@Override
protected void handObserver() {
super.handObserver();
viewModel.liveData.observe(this, foodEntity -> {
if (foodEntity.getCode()==200){
list.addAll(foodEntity.getData());
adapter=new FoodAdapter(R.layout.view_food,list);
viewDataBinding.rv.setAdapter(adapter);
}
});
}
}
登录注册
先写Model应用层的Model继承BaseModel(方法可从Api中复制):
package com.bw.day3.MVVM.User.Login;
import com.bw.day3.MVVM.Base.Entity.UserEntity;
import com.bw.day3.MVVM.Base.Model.BaseModel;
import io.reactivex.Observable;
import okhttp3.RequestBody;
public class LoginModel extends BaseModel {
public Observable<UserEntity> postLoginData(RequestBody body){
return api.postLoginData(body);
}
}
再写ViewModel(继承BaseViewModel泛型为应用层的Model):
package com.bw.day3.MVVM.User.Login;
import androidx.lifecycle.MutableLiveData;
import com.bw.day3.MVVM.Base.Entity.UserEntity;
import com.bw.day3.MVVM.Base.ViewModel.BaseViewModel;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
public class LoginViewModel extends BaseViewModel<LoginModel> {
public MutableLiveData<UserEntity> liveData=new MutableLiveData<>();
@Override
protected LoginModel creatModel() {
return new LoginModel();
}
public void postLoginData(RequestBody body){
bModel.postLoginData(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<UserEntity>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UserEntity userEntity) {
liveData.postValue(userEntity);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
最后写View层Activity
package com.bw.day3.MVVM.User.Login;
import android.content.Intent;
import android.widget.Toast;
import com.bw.day3.MVVM.Base.View.BaseActivity;
import com.bw.day3.MVVM.User.Register.RegisterActivity;
import com.bw.day3.R;
import com.bw.day3.databinding.ActivityLoginBinding;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.RequestBody;
public class LoginActivity extends BaseActivity<ActivityLoginBinding,LoginViewModel> {
@Override
protected Class<LoginViewModel> getViewModel() {
return LoginViewModel.class;
}
@Override
protected int getLayoutid() {
return R.layout.activity_login;
}
@Override
protected void initView() {
viewDataBinding.login.setOnClickListener(v -> {
String username=viewDataBinding.username.getText().toString().trim();
String password=viewDataBinding.password.getText().toString().trim();
Map<String,String> map=new HashMap<>();
map.put("username",username);
map.put("password",password);
String json=new Gson().toJson(map);
RequestBody requestBody=RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json);
viewModel.postLoginData(requestBody);
});
viewDataBinding.register.setOnClickListener(v -> {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
});
}
@Override
protected void initData() {
}
@Override
protected void handObserver() {
super.handObserver();
viewModel.liveData.observe(this, userEntity -> {
if (userEntity.getCode()==200){
Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "登录失败:"+userEntity.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
所需依赖build.gradle中添加:
viewBinding {
enabled = true
}
dataBinding {
enabled = true
}
implementation 'com.google.code.gson:gson:2.8.0'//gson依赖
//RxJava依赖:主要用于消息传递
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
//Retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
//Gson converter gson解析
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
//RxJava2 Adapter
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
//okhttp
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
//rxlifecycle异步线程生命周期管理
implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.1'
//rxpermissions
implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.0'//万能适配器
implementation 'com.android.support:recyclerview-v7:30.0.0'//recyclerview