Mvp登入與資訊展示
首先是登入主頁面
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText ed_name;
private EditText ed_password;
private CheckBox check_jz;
private Button btn_login;
private SharedPreferences mSp;
private boolean mIscheck_jz;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
mSp = getSharedPreferences("cmf", MODE_PRIVATE);
mIscheck_jz = mSp.getBoolean("ischeck_jz", false);
String name = mSp.getString("name", "");
String pwd = mSp.getString("pwd", "");
if (mIscheck_jz){
ed_name.setText(name);
ed_password.setText(pwd);
check_jz.setChecked(true);
}
}
private void initView() {
ed_name = (EditText) findViewById(R.id.ed_name);
ed_password = (EditText) findViewById(R.id.ed_password);
check_jz = (CheckBox) findViewById(R.id.check_jz);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(this);
}
@SuppressLint("CommitPrefEdits")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
String mname = ed_name.getText().toString().trim();
String mpwd = ed_password.getText().toString().trim();
if (TextUtils.isEmpty(mname)||TextUtils.isEmpty(mpwd)){
Toast.makeText(MainActivity.this,"登陸失敗",Toast.LENGTH_SHORT).show();
}else {
if(check_jz.isChecked()){
SharedPreferences.Editor edit=mSp.edit();
edit.putString("name",mname);
edit.putString("pwd",mpwd);
edit.putBoolean("ischeck_jz",true);
edit.commit();
}
Toast.makeText(MainActivity.this,"登陸成功",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, ShowActivity.class);
startActivity(intent);
}
break;
}
}
}
其次是資訊展示頁面的佈局檔案
public class ShowActivity extends AppCompatActivity implements MyView {
public int REQUEST_CODE = 5;//掃描二維碼
private ImageView mSaoYiSao;
private GridView mGridViewImg;
private ViewFlipper mViewFlipper;
private GridView mGridViewShop;
private ArrayList<Sudoku.DataBean> sList;
private ArrayList<Datas.DataBean> dList;
private MyPrenter mMyPrenter;
private RecyclerView mRecyclerview;
private RecyclerView mRecyclerViewJ;
private SudokuAdapter mSudokuAdapter;
private DatasAdapter mDatasAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
initView();
//2 跑馬燈設定
setViewFlipper();
//3 點選掃一掃設定
setQTCode();
//4 九宮格 設定
setJGGAndShop();
}
private void setJGGAndShop() {
//建立一個List
sList = new ArrayList<>();//九宮格
dList = new ArrayList<>();//shop商品
//adapter 另一種形式
mSudokuAdapter = new SudokuAdapter(this, sList);
mDatasAdapter = new DatasAdapter(this, dList);
//另一種形式
mRecyclerViewJ.setAdapter(mSudokuAdapter);
mRecyclerview.setAdapter(mDatasAdapter);
//5 初始化presenter層
mMyPrenter = new MyPrenter();
mMyPrenter.attach(this);
mMyPrenter.getPData();
mMyPrenter.getShopData();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//二維碼掃描返回結果
if(requestCode == REQUEST_CODE){
if(null != data){
Bundle bundle = data.getExtras();
if(bundle == null){
return;
}
if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
String result = bundle.getString(CodeUtils.RESULT_STRING);
Toast.makeText(ShowActivity.this,"解析結果:"+result,Toast.LENGTH_SHORT).show();
}else if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED){
Toast.makeText(ShowActivity.this,"解析失敗!",Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* //3 點選掃一掃設定
* */
private void setQTCode() {
mSaoYiSao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//進行跳轉
Intent intent = new Intent(ShowActivity.this, CaptureActivity.class);
startActivityForResult(intent,REQUEST_CODE);
}
});
}
/**
* //2 跑馬燈設定
* */
private void setViewFlipper() {
//使用for迴圈新增
for (int i = 0; i < 3; i++) {
if(i==0){
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.viewflipper_1,null);
mViewFlipper.addView(view);
}else if(i==1){
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.viewflipper_2,null);
mViewFlipper.addView(view);
}else if(i==2){
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.viewflipper_3,null);
mViewFlipper.addView(view);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mMyPrenter != null) {
mMyPrenter.datach();
}
}
private void initView() {
mSaoYiSao = (ImageView) findViewById(R.id.saoyisao);
mRecyclerViewJ = (RecyclerView) findViewById(R.id.recyclerviewJ);
mViewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
mRecyclerview = (RecyclerView) findViewById(R.id.recyclerview);
RecyclerView.LayoutManager layoutManagerJ = new StaggeredGridLayoutManager(3,LinearLayoutManager.VERTICAL);
mRecyclerViewJ.setLayoutManager(layoutManagerJ);
//瀑布流
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2,LinearLayoutManager.HORIZONTAL);
mRecyclerview.setLayoutManager(layoutManager);//佈局
//分割線
// mRecyclerview.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
//動畫
mRecyclerview.setItemAnimator(new DefaultItemAnimator());
}
@Override
public void Sudoku(ArrayList<Sudoku.DataBean> list) {
if(list!=null){
sList.clear();
sList.addAll(list);
mSudokuAdapter.notifyDataSetChanged();
}
}
@Override
public void ProductData(ArrayList<Datas.DataBean> list) {
if(list!=null){
dList.clear();
dList.addAll(list);
mDatasAdapter.notifyDataSetChanged();
}
}
@Override
public void Friand(Exception e) {
Toast.makeText(ShowActivity.this,"網路異常",Toast.LENGTH_SHORT).show();
}
}
兩個介面其中一個介面中有3個方法另一個是兩個
public interface MyView{
void Sudoku(ArrayList<Sudoku.DataBean> list);
void ProductData(ArrayList<Datas.DataBean> list);
void Friand(Exception e);
}
public interface MyCallback {
void OnSuccess(Object o);
void OnFriand(Exception e);
}
然後就是寫實體類,然後就是寫網路請求工具類的程式碼我採用的okhttp
public class OKHttputil {
//定義一個工具類物件
private static volatile OKHttputil sOKHttputil;
private final OkHttpClient mOkHttpClient;
private Handler mHandler = new Handler();
//建立一個無參構造方法
public OKHttputil(){
mOkHttpClient = new OkHttpClient();
}
//建立一個公共的靜態方法
public static OKHttputil getOKHttputil(){
if (sOKHttputil==null){
synchronized (OKHttputil.class){
if (null==sOKHttputil){
sOKHttputil=new OKHttputil();
}
}
}
return sOKHttputil;
}
//定義一個請求資料的方法
public void getData(String url, final MyCallback myCallback, final Type type){
Request request = new Request.Builder()
.get()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
myCallback.OnFriand(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Gson gson = new Gson();
final Object o = gson.fromJson(string, type);
mHandler.post(new Runnable() {
@Override
public void run() {
myCallback.OnSuccess(o);
}
});
}
});
}
}
緊接著是寫一個model層去呼叫網路工具類的獲得資料的方法
public class MyModel {
//定義一個m層請求資料的方法
public void getMData(String url, MyCallback myCallback, Type type){
OKHttputil.getOKHttputil().getData(url,myCallback,type);
}
}
然後就是書寫p層邏輯程式碼,在p層呼叫m層請求資料程式碼,p層中有一個view層和model層互動的方法以及一個銷燬的方法
public class MyPrenter {
//建立view和model物件
private MyView mMyView;
private MyModel mMyModel;
//初始化物件
public void attach(MyView myView){
this.mMyView=myView;
mMyModel=new MyModel();
}
//定義一個p層得到資料的方法
public void getPData(){
//初始化Type 泛型
Type type = new TypeToken<Sudoku>(){}.getType();
//呼叫登入方法 並實現方法
mMyModel.getMData("http://www.zhaoapi.cn/product/getCatagory", new MyCallback() {
@Override
public void OnSuccess(Object o) {
Sudoku sudoku = (Sudoku) o;
ArrayList<Sudoku.DataBean> data = (ArrayList<Sudoku.DataBean>) sudoku.getData();
if(sudoku!=null) {
mMyView.Sudoku(data);
}
}
@Override
public void OnFriand(Exception e) {
mMyView.Friand(e);
}
}, type);
}
public void getShopData(){
//初始化Type 泛型
Type type = new TypeToken<Datas>(){}.getType();
//呼叫登入方法 並實現方法
mMyModel.getMData("http://www.wanandroid.com/tools/mockapi/6523/restaurants_offset_0_limit_4", new MyCallback() {
@Override
public void OnSuccess(Object o) {
Datas shopBean = (Datas) o;
if(shopBean!=null){
ArrayList<Datas.DataBean> data = (ArrayList<Datas.DataBean>) shopBean.getData();
mMyView.ProductData(data);
}
}
@Override
public void OnFriand(Exception e) {
mMyView.Friand(e);
}
}, type);
}
//解綁的方法
public void datach(){
if (mMyView!=null){
mMyView=null;
}
}
}
介面卡,因為我的佈局檔案中用的是RecyclerView用來代替listview
public class SudokuAdapter extends RecyclerView.Adapter<SudokuAdapter.ViewHolder> {
private Context mContext;
private ArrayList<Sudoku.DataBean> list;
public SudokuAdapter(Context context, ArrayList<Sudoku.DataBean> list) {
mContext = context;
this.list=list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v=View.inflate(mContext,R.layout.item_jiugongge,null);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.mTxtTitle.setText(list.get(position).getName());
Glide.with(mContext).load(list.get(position).getIcon()).into(holder.mJiuGongGe);
}
@Override
public int getItemCount() {
return list.size();
}
//1 需要一個Adapter
class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView mJiuGongGe;
private final TextView mTxtTitle;
public ViewHolder(View itemView) {
super(itemView);
//找控制元件
mJiuGongGe = itemView.findViewById(R.id.jiugongge_img);
mTxtTitle = itemView.findViewById(R.id.txt_title);
}
}
}
public class DatasAdapter extends RecyclerView.Adapter<DatasAdapter.ViewHolder> {
private Context mContext;
private ArrayList<Datas.DataBean> list;
public DatasAdapter(Context context, ArrayList<Datas.DataBean> list) {
mContext = context;
this.list = list;
}
//2 實現三個方法
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//在建立的時候 做初始化的方法 View 和 holder的初始化
View v = View.inflate(mContext, R.layout.item_shop,null);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//繫結的方法 用來設定控制元件的值
holder.mTxtTitle.setText(list.get(position).getName());
Glide.with(mContext).load(list.get(position).getPic_url()).into(holder.mImg);
}
@Override
public int getItemCount() {
return list.size();
}
//1 需要一個Adapter
class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView mImg;
private final TextView mTxtTitle;
public ViewHolder(View itemView) {
super(itemView);
//找控制元件
mImg = itemView.findViewById(R.id.img);
mTxtTitle = itemView.findViewById(R.id.txt_title);
}
}
}
全域性配置的一個類
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ZXingLibrary.initDisplayOpinion(this);
}
}
這是資訊展示頁面的佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ShowActivity">
//shop介面
//top
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="6"
android:background="#f00"
>
//二維碼掃描
<ImageView
android:id="@+id/saoyisao"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/a_s"
/>
<android.support.v7.widget.SearchView
android:layout_width="0dp"
android:layout_weight="5"
android:layout_height="wrap_content"
android:background="@drawable/bg_searchview"
app:queryHint="搜尋"
></android.support.v7.widget.SearchView>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:text="商品分類"
android:layout_gravity="center"
android:gravity="center"
android:textColor="#000"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
//資料塊
<!--<GridView
android:id="@+id/gridview_img"
android:layout_width="match_parent"
android:layout_height="150dp"
android:numColumns="3"
></GridView>-->
//九宮格使用的另一種控制元件
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerviewJ"
android:layout_width="match_parent"
android:layout_height="200dp"
>
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7"
android:layout_margin="10dp"
>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="公告:"
android:textSize="20dp"
android:background="#f99b43"
/>
//跑馬燈效果
<ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000"
android:inAnimation="@anim/anto_start_anim"
android:outAnimation="@anim/anto_out_anim"
android:layout_marginLeft="15dp"
></ViewFlipper>
</LinearLayout>
//商品展示
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2"
>
<!--<GridView
android:id="@+id/gridview_shop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2"
></GridView>-->
//另一種方式展示
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
這是demo中用的的許可權
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
app目錄下的gradle檔案
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '27.1.1' //這裡改為你專案使用的版本即可
}
}
}
}
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'cn.yipianfengye.android:zxing-library:2.2'
implementation 'com.android.support:recyclerview-v7:27.1.1'
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}