一直以来都是特别的推崇其他人的mvp的架构模式,好不容易从网上找到了一篇经典的代码,效果特别不错
1,首先配置一下工程的配置
在build.gradle 内写上
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.google.code.gson:gson:2.7'
这样的话,就可以增加okhttp 和butternife 这两个关键的jar包。
2,在配置文件内增加需要的权限,比如网络的配置
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
3,配置layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="手机号查询"
android:textColor="@color/colorAccent" />
<EditText
android:id="@+id/input_phone"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="20dp"
android:hint="请输入手机号"
android:inputType="phone"
android:textColor="@color/colorAccent"
android:textColorHint="@color/hint_color" />
<Button
android:id="@+id/button_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="10dp"
android:text="立即查询"
android:textColor="@color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="查询结果"
android:textColor="@color/colorAccent"
android:textSize="18sp" />
<TextView
android:id="@+id/result_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="15dp"
android:text="手机号:" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/main_background" />
<TextView
android:id="@+id/result_province"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="省和市:" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/main_background" />
<TextView
android:id="@+id/result_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="运营商:" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/main_background" />
<TextView
android:id="@+id/result_carrier"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="卡类型:" />
</LinearLayout>
当然了,在这里面,还要将value的颜色进行一下配置
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#3F51B5</color>
<color name="colorAccent">#FF4081</color>
<!-- 背景颜色 -->
<color name="main_background">#eeeeee</color>
<!-- 标题文字颜色 -->
<color name="title_txt_color">#808080</color>
<!-- 输入框提示文字颜色 -->
<color name="hint_color">#bfbfc1</color>
<!-- 查询结果标题文字颜色 -->
<color name="search_title_color">#4a4a4a</color>
</resources>
4,开始正式的代码编写
4.1在mainactivity 内誊写程序
package nfc.com.mytelephone;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nfc.com.mytelephone.model.Phone;
import nfc.com.mytelephone.mvp.MvpMainView;
import nfc.com.mytelephone.mvp.impl.MainPresenter;
public class MainActivity extends Activity implements MvpMainView {
MainPresenter mainPresenter;
ProgressDialog progressDialog;
//butterknife注入
@BindView(R.id.input_phone)
EditText inputPhone;
@BindView(R.id.button_search)
Button buttonSearch;
@BindView(R.id.result_phone)
TextView resultPhone;
@BindView(R.id.result_province)
TextView resultProvince;
@BindView(R.id.result_type)
TextView resultType;
@BindView(R.id.result_carrier)
TextView resultCarrier;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mainPresenter = new MainPresenter(this);
mainPresenter.attach(this);
}
@OnClick(R.id.button_search)
public void onViewClicked() {
//查询
mainPresenter.searchPhoneInfo(inputPhone.getText().toString());
}
@Override
public void showLoading() {
if (progressDialog == null) {
} else if (progressDialog.isShowing()) {
progressDialog.setTitle("");
progressDialog.setMessage("正在查询...");
}
}
@Override
public void hidenLoading() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void updateView() {
Phone phone = mainPresenter.getPhoneInfo();
resultPhone.setText("手机号:" + inputPhone.getText().toString());
resultProvince.setText("省和市:" + phone.getProvince() );
resultType.setText("运营商:" + phone.getCastName());
resultCarrier.setText("卡类型:" + phone.getCarrier());
}
}
4。2 需要的两个接口 MvpMainView,BasePresenter
public interface MvpLodingView {
void showLoading();
void hidenLoading();
}
他们是分别写在了两个类里面了
public interface MvpMainView extends MvpLodingView{
void showToast(String msg);
void updateView();
}
4。3需要的网络协议写的类
public class HttpUtil {
private static final String APIKEY = "http://apistore.baidu.com/apiworks/servicedetail/498.html";
String mUrl;
Map<String, String> mParm;
HttpResponse mHttpResponse;
private final OkHttpClient client = new OkHttpClient();
//全局handler
Handler mHandler = new Handler(Looper.getMainLooper());
//http请求回调
public interface HttpResponse {
void onSuccess(Object object);
void onFail(String error);
}
//http回调函数
public HttpUtil(HttpResponse mHttpResponse) {
this.mHttpResponse = mHttpResponse;
}
public void sendPostHttp(String url, Map<String, String> parm) {
sendHttp(url, parm, true);
}
public void sendGettHttp(String url, Map<String, String> parm) {
sendHttp(url, parm, false);
}
private void sendHttp(String url, Map<String, String> parm, boolean isPost) {
mUrl = url;
mParm = parm;
//HTTP请求逻辑
run(isPost);
}
private void run(boolean isPost) {
final Request request = createRequest(isPost);
//创建请求队列
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (mHttpResponse != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mHttpResponse.onFail("请求错误");
}
});
}
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (mHttpResponse == null) {
return;
}
mHandler.post(new Runnable() {
@Override
public void run() {
if (!response.isSuccessful()) {
mHttpResponse.onFail("请求失败:code" + response);
} else {
try {
mHttpResponse.onSuccess(response.body().string());
} catch (IOException e) {
e.printStackTrace();
mHttpResponse.onFail("结果转换失败");
}
}
}
});
}
});
}
4。4主要使用的类
基类
public class BasePresenter {
Context mContext;
public void attach(Context context) {
mContext = context;
}
public void onPause() {
}
public void onResume() {
}
public void onDestroy() {
mContext = null;
}
}
主要的类
public class MainPresenter extends BasePresenter {
String httpUrl = "http://apis.baidu.com/netpopo/shouji/query";
MvpMainView mvpMainView;
Phone mPhone;
public Phone getPhoneInfo() {
return mPhone;
}
public MainPresenter(MvpMainView mainView) {
mvpMainView = mainView;
}
public void searchPhoneInfo(String phone) {
if (phone.length() != 11) {
mvpMainView.showToast("请输入正确的手机号");
return;
}
mvpMainView.showLoading();
//http请求
sendHttp(phone);
}
private void sendHttp(String phone) {
Map<String, String> map = new HashMap<>();
map.put("shouji", phone);
HttpUtil httpUtil = new HttpUtil(new HttpUtil.HttpResponse() {
@Override
public void onSuccess(Object object) {
String json = object.toString();
Log.i("123", "返回json数据: " + json);
mPhone = parseModelWithGson(json);
mvpMainView.hidenLoading();
mvpMainView.updateView();
}
@Override
public void onFail(String error) {
mvpMainView.showToast(error);
mvpMainView.hidenLoading();
}
});
httpUtil.sendGettHttp(httpUrl, map);
}
/**
* 使用Gson解析返回的json数据
*
* @param json
* @return
*/
private Phone parseModelWithGson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, Phone.class);
}
}
4。5里面的电话的类,phone类
public class Phone {
String number;
String province;
String castName;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCastName() {
return castName;
}
public void setCastName(String castName) {
this.castName = castName;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
String carrier;
}
代码整理结束,每天都需要参考巩固一下,相信会很快掌握这个技术