public class ShouYeActivity extends AppCompatActivity implements ShowView {
private RecyclerView rlv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shou_ye);
rlv = findViewById(R.id.rlv);
//创建布局管理器
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//设置布局管理器
rlv.setLayoutManager(linearLayoutManager);
//采用MVP
//采用presenter
ShowPresenter presenter=new ShowPresenter(this);
//关联 是为了使用弱引用管理外部类对象
presenter.related();
}
//view层获取到数据
public void show(JSONArray result) {
//把数据给适配器
Madapter madapter = new Madapter(this, result);
rlv.setAdapter(madapter);
}
}
/M层
public class ShowModel {
private String url = "http://172.17.8.100/small/commodity/v1/bannerShow";
//回调接口
public interface OnShowListener {
void onShow(JSONArray result);
}
//实例化
private OnShowListener lisenter;
public void setOnShowListener(OnShowListener lisenter) {
this.lisenter = lisenter;
}
//handler处理机制
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
String json = (String) msg.obj;
//Json解析
try {
JSONObject array = new JSONObject(json);
JSONArray result = array.getJSONArray("result");
if (lisenter != null) {
lisenter.onShow(result);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
};
//1.获取网络数据
public void getGoodsData() {
OkHttpUtils.getInstance().doGet(url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
//成功
@Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
//handler发送数据
Message message = new Message();
message.what = 0;
message.obj = json;
handler.sendMessage(message);
}
});
}
}
///P层
public class ShowPresenter {
private final ShowModel showModel;
private final ShowView showView;
private WeakReference<T> mViewRef;
//构造方法中实例化showModel和showView
public ShowPresenter(ShowView view) {
showModel = new ShowModel();
showView = view;
}
//在P层中使用WeakReference管理外部对象
public void attachView(T t) {
//创建弱引用
mViewRef = new WeakReference<>(t);
}
//1.P关联M层
public void related() {
showModel.getGoodsData();
showModel.setOnShowListener(new ShowModel.OnShowListener() {
@Override
public void onShow(JSONArray result) {
//把数据给V
showView.show(result);
}
});
}
//解除关联
public void detachView() {
if (mViewRef.get() != null) {
mViewRef.clear();
mViewRef = null;
}
}
}
V层
public interface ShowView {
void show(JSONArray result);
}