本文共 3215 字,大约阅读时间需要 10 分钟。
项目结构:
视图层通过presenter调用模型来获取数据,模型调用retrofit获得数据后,再通过CallBack把数据返回给presenter,presenter通过Impl返回给view,view负责显示就行,逻辑层次明显。
首先要添加相关依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.2'compile 'com.squareup.retrofit2:converter-gson:2.0.2'
model来实现业务操作:
public class PeotryModel { //测试接口 private String POST_STR = "http://api.apiopen.top/"; //new 一个retrofit对象 Retrofit retrofit = new Retrofit.Builder().baseUrl(POST_STR) .addConverterFactory(GsonConverterFactory.create()) .build(); //获取古诗信息 public void getPeotry(String name, final PeotryCallBack peotryCallBack) { final PeotryApi peotryApi = retrofit.create(PeotryApi.class); CallpeotryBeamCall = peotryApi.peotryBeamPost(name); peotryBeamCall.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { PeotryBeam peotryBeam = response.body(); peotryCallBack.onSucceess(peotryBeam); } @Override public void onFailure(Call call, Throwable t) { peotryCallBack.onFailed(); } }); }}
presenter进行传递:
public class PeotryPresenter { private PeotryImpl peotryImpl; private PeotryModel peotryModel; public PeotryPresenter(PeotryImpl peotryImpl) { this.peotryImpl = peotryImpl; peotryModel = new PeotryModel(); } public void getData(String name) { peotryModel.getPeotry(name, new PeotryCallBack() { @Override public void onSucceess(PeotryBeam peotryBeam) { peotryImpl.onSuccess(peotryBeam); } @Override public void onFailed() { peotryImpl.onFailed(); } }); }}
view负责显示数据:
public class MainActivity extends AppCompatActivity implements View.OnClickListener, PeotryImpl { private EditText inputEt; private Button getBtn; private TextView resultTv; private PeotryPresenter peotryPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); peotryPresenter = new PeotryPresenter(this); } private void initView() { inputEt = findViewById(R.id.input_et); getBtn = findViewById(R.id.get_btn); resultTv = findViewById(R.id.result_tv); getBtn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.get_btn: peotryPresenter.getData(getUserInput()); break; } } @Override public String getUserInput() { return inputEt.getText().toString(); } @Override public void onSuccess(PeotryBeam peotryBeam) { resultTv.setText(peotryBeam.getMessage() + "\n" + peotryBeam.getResult()); } @Override public void onFailed() { resultTv.setText("获取失败"); }}
作者:Sam
资源地址:https://download.csdn.net/download/Jeyden_827/12264774
每日一笑:
情人节那天,老公深情的问老婆:宝贝儿,我送你什么好?老婆低着头笑着说:你送什么我都喜欢。老公含情脉脉的说:亲爱的,既然我送什么你都喜欢,那我送你回娘家吧!过几天我再接你回来。
转载地址:http://wwrgf.baihongyu.com/