登录注册展示mvp RecyclerView单条目和多条目


 	//1依赖
    implementation 'com.android.support:recyclerview-v7:28.+'
    implementation 'com.squareup.okio:okio:1.5.0'
    implementation 'com.squareup.okhttp3:okhttp:3.2.0'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    //2权限
     <uses-permission android:name="android.permission.INTERNET"/>
    
    //3main布局
    <?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=".acitivity.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:text="商品展示" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rlv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>


</LinearLayout>

 
//4mainactivity  展示
public class MainActivity extends AppCompatActivity implements ShowView {

    private RecyclerView rlv;
    private ShowPresenter showPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找控件
        rlv = findViewById(R.id.rlv);
        //创建布局管理器
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        //设置布局
        rlv.setLayoutManager(linearLayoutManager);

        //创建p
        showPresenter = new ShowPresenter(this);

        //关联 目的是为了使用弱引用管理外部类对象
        showPresenter.attachView(MainActivity.this);

        //创建关联的方法
        showPresenter.related();
 }

    @Override
    public void view(JSONArray result) {
             //把数据给适配器
      //  MyAdapter myAdapter = new MyAdapter(this,result);
        MyDuoAdapter myDuoAdapter = new MyDuoAdapter(this, result);
        rlv.setAdapter(myDuoAdapter);
        myDuoAdapter.setOnDuoclick(new MyDuoAdapter.OnDuoclick() {
            @Override
            public void onclik(int i) {
                Toast.makeText(MainActivity.this, "单击事件", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(int i) {
                Toast.makeText(MainActivity.this, "长按事件", Toast.LENGTH_SHORT).show();
            }
        });
    }


    //解决mvp造成的内存泄漏
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //activity销毁之前p得先销毁
        showPresenter.detachView();
        Log.i("xxx", "销毁了");

    }
}

//ShowPresenter
public class ShowPresenter<T>{

    private final ShowModel showModel;
    private final ShowView showView;
    protected Reference<T> mViewRef;//View接口类型弱引用

    public ShowPresenter(ShowView view) {
        showModel = new ShowModel();
        showView = view;
    }


    //在p层使用WeakReference管理外部类对象
    public void attachView(T t) {
        //创建弱引用
        mViewRef = new WeakReference<T>(t);
    }


    //p关联m
    public void related() {
        //m有个方法 获得数据
        showModel.getGoodsData();
        showModel.setOnShowListener(new ShowModel.OnShowListener() {
            @Override
            public void onResult(JSONArray result) {
                showView.view(result);
            }
        });

    }

    //解除关联
    public void detachView() {
        if (mViewRef.get() != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }


}
//ShowModel
public class ShowModel {
  
    String url = "http://172.17.8.100/small/commodity/v1/bannerShow";
	//接口回调
    public interface OnShowListener {
        void onResult(JSONArray result);
    }

    private OnShowListener onShowListener;

    public void setOnShowListener(OnShowListener onShowListener) {
        this.onShowListener = onShowListener;
    }

    //网络数据
    public void getGoodsData() {

        HttpUtils.getInstence().doGet(url, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                //创建对象
                Message message = new Message();
                message.what = 0;
                message.obj = string;
                handler.sendMessage(message);
            }
        });

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                     try {
                        JSONObject jsonObject = new JSONObject(obj);
                        JSONArray result = jsonObject.getJSONArray("result");
                        if (onShowListener != null) {
                            onShowListener.onResult(result);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
            }
        }
    };


}

//封装网络工具类
public class HttpUtils {

    private static  HttpUtils httpUtils=null;

    public HttpUtils() {
    }

    //返回实例的方法
    public static HttpUtils getInstence(){
        if(httpUtils==null){
            //同步锁
            synchronized (HttpUtils.class){
                if(httpUtils==null){
                    httpUtils=new HttpUtils();
                }
            }

        }
        return httpUtils;

    }

    //创建get请求封装的方法
    public static  void  doGet(String url, Callback callback){
          //创建日志拦截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("xx",message);
            }
        });
        //指定日志拦截器模式
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //创建okhttpclient
        OkHttpClient okHttpClient=new  OkHttpClient.Builder()
                //添加拦截
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Request request=new Request.Builder()
                .url(url)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);



    }



}
//ShowView
public interface ShowView {
    void view(JSONArray result);
}
------------------------------------------------------------------------
//登录
public class DengLu extends AppCompatActivity implements View.OnClickListener,LoginView {
    private EditText et1;
    private EditText et2;
    private Button login;
    private Button reg;
    private String phone;
    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deng_lu);
        //登錄接口
        //获取控件
        et1 = findViewById(R.id.et1);
        et2 = findViewById(R.id.et2);
        login = findViewById(R.id.login);
        reg = findViewById(R.id.reg);

        //点击登录注册
        login.setOnClickListener(this);
        //点击注册事件
        reg.setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                //获得内容
                phone = et1.getText().toString();
                pwd = et2.getText().toString();
                boolean mobileNO = Util.isMobileNO(phone);
                if(mobileNO){
                    if(pwd.length()<3){
                        Toast.makeText(DengLu.this, "密码不对", Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                       //创建LoginPresenter
                        LoginPresenter loginPresenter=new LoginPresenter(this);
                        loginPresenter.send(phone,pwd);
                    }
                }else{
                    Toast.makeText(DengLu.this, "手机号格式不对", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.reg:
                //跳转
                Intent intent = new Intent(DengLu.this,ZhuCe.class);
                startActivity(intent);

                break;

        }
    }

    @Override
    public void view(String message) {
        if(message.equals("登录成功")){
            Intent intent = new Intent(DengLu.this, MainActivity.class);
            startActivity(intent);
        }else{
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
        }

    }
}
//正则工具列类
public class Util {
    public static boolean isMobileNO(String mobiles) {
        boolean isValid = false;
        CharSequence inputStr = mobiles;
        // 正则表达式

        String phone = "^1[34578]\\d{9}$";

        Pattern pattern = Pattern.compile(phone);
        Matcher matcher = pattern.matcher(inputStr);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

}


//LoginPresenter 
public class LoginPresenter {

    private final LoginModel loginModel;
    private final LoginView loginView;

    public LoginPresenter(LoginView view) {
        //创建LoginModel
        loginModel = new LoginModel();
        loginView = view;
    }

    public void send(String phone, String pwd) {
        loginModel.login(phone,pwd);
        loginModel.setOnLoginListener(new LoginModel.OnLoginListener() {
            @Override
            public void onMessage(String message) {
                loginView.view(message);
            }
        });
    }
}
//LoginModel 
public class LoginModel {
    //接口回调传数据
    public interface OnLoginListener {
        void onMessage(String message);
    }

    private OnLoginListener onLoginListener;

    public void setOnLoginListener(OnLoginListener onLoginListener) {
        this.onLoginListener = onLoginListener;
    }

    //OkHttp请求登录接口获得数据
    public void login(String phone, String pwd) {
        //通过OKHttp获取网络数据
        //1创建OkHttp对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2创建RequestBody请求体,封装参数
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .add("pwd", pwd)
                .build();
        //3创建request请求
        Request request = new Request.Builder()
                .url("http://172.17.8.100/small/user/v1/login")
                .post(formBody)
                .build();
        //4执行请求
        Call call = okHttpClient.newCall(request);
        //5执行异步
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message message = new Message();
                message.what = 0;
                message.obj = string;
                handler.sendMessage(message);
            }
        });
    }


    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    try {
                        String obj = (String) msg.obj;
                        JSONObject  jsonObject = new JSONObject(obj);
                        String message = jsonObject.getString("message");
                        //给接口数据
                        if (onLoginListener != null) {
                            onLoginListener.onMessage(message);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
            }
        }
    };
}
---------------------------------------------------------------------------
//注册
public class ZhuCe extends AppCompatActivity  implements View.OnClickListener,RegView {
    private EditText et1;
    private EditText et2;
    private Button bt1;
    private String et_phone;
    private String pwd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhu_ce);

        //获取控件
        et1 = findViewById(R.id.et1);
        et2 = findViewById(R.id.et2);
        bt1 = findViewById(R.id.bt1);


        //点击注册
        bt1.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        //获得内容
        et_phone= et1.getText().toString();
        pwd = et2.getText().toString();
        //正则工具验证
        boolean mobileNO = Util.isMobileNO(et_phone);
        if(mobileNO){
            if(pwd.length()<3){
                Toast.makeText(ZhuCe.this, "密码不能小于3位", Toast.LENGTH_SHORT).show();
                return;
            }else{
                //创建RegPresenter
                RegPresenter regPresenter=new RegPresenter(this);
                regPresenter.send(et_phone,pwd);
            }
        }else{
            Toast.makeText(ZhuCe.this, "手机号格式不对", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    @Override
    public void onMessage(String message) {
            if(message.equals("注册成功")){
                //跳转
                Intent intent = new Intent(ZhuCe.this,DengLu.class);
                startActivity(intent);
            }else{
                Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            }
    }
}

//RegPresenter 
public class RegPresenter {

    private final RegModel regModel;
    private final RegView regView;

    public RegPresenter(RegView view) {
        regModel = new RegModel();
        regView = view;
    }

    public void send(String phone, String pwd) {
       regModel.reg(phone,pwd);
       regModel.setOnLoginListener(new RegModel.OnRegListener() {
           @Override
           public void onMessage(String message) {
               regView.onMessage(message);
           }
       });

    }

}

//RegModel 
public class RegModel {
    //接口回调传数据
    public interface OnRegListener {
        void onMessage(String message);
    }

    private OnRegListener onRegListener;

    public void setOnLoginListener(RegModel.OnRegListener onRegListener) {
        this.onRegListener = onRegListener;
    }

    //OkHttp请求注册接口获得数据
     public void reg(String phone, String pwd) {
        //注册的接口
        String registerUrl="http://172.17.8.100/small/user/v1/register";
         //通过OKHttp获取网络数据
        //1创建OkHttp对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //2创建RequestBody请求体,封装参数
        FormBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .add("pwd", pwd)
                .build();
        //3创建request请求
        final Request request = new Request.Builder().url(registerUrl).post(requestBody).build();
        //4执行请求
        Call call = okHttpClient.newCall(request);
        //5执行异步
        call.enqueue(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();
                //传消息
                Message message=new Message();
                message.what=0;
                message.obj=json;
                handler.sendMessage(message);

            }
        });

    }

    //接受消息
    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String obj= (String) msg.obj;
                    Log.d("xxx",obj);
                    try {
                        JSONObject jsonObject = new JSONObject(obj);
                        String message = jsonObject.getString("message");
                        if(onRegListener!=null){
                            onRegListener.onMessage(message);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };


}

//RegView 
public interface RegView {
    void onMessage(String message);
}

//单条目适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private JSONArray result;
    private Context context;
    //构造传参
    public MyAdapter(Context context, JSONArray result) {
        this.context=context;
        this.result=result;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itme, null, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
            //数据
        try {
            JSONObject jsonObject = result.getJSONObject(i);
            String title = jsonObject.getString("title");
            String imageUrl = jsonObject.getString("imageUrl");
            //赋值
            viewHolder.tv.setText(title);
            Glide.with(context).load(imageUrl).into(viewHolder.img);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public int getItemCount() {
        return result.length();
    }
    //自定义的ViewHolder
    public  class ViewHolder  extends RecyclerView.ViewHolder{

        private final TextView tv;
        private final ImageView img;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = itemView.findViewById(R.id.tv);
            img = itemView.findViewById(R.id.img);
        }
    }
}


//多条适配器
public class MyDuoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private JSONArray result;
    private Context context;
    private final static int TYPE_ONE=0;
    private final static int TYPE_TWO=1;

    //构造传参
    public MyDuoAdapter(Context context, JSONArray result) {
        this.context=context;
        this.result=result;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        int type = getItemViewType(i);
        if(type==TYPE_ONE){
            View view = LayoutInflater.from(context).inflate(R.layout.itme, null, false);
            ViewHodlder1 viewHodlder1 = new ViewHodlder1(view);
            return viewHodlder1;
        }else{
            View view = LayoutInflater.from(context).inflate(R.layout.itme1, null, false);
            ViewHodlder2 viewHodlder2 = new ViewHodlder2(view);
            return viewHodlder2;
        }


    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) {
            if(viewHolder instanceof ViewHodlder1){
                //数据
                try {
                    JSONObject jsonObject = result.getJSONObject(i);
                    String title = jsonObject.getString("title");
                    String imageUrl = jsonObject.getString("imageUrl");
                    //赋值
                    ((ViewHodlder1) viewHolder).text.setText(title);
                    Glide.with(context).load(imageUrl).into(((ViewHodlder1) viewHolder).img);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //单机事件
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onDuoclick.onclik(i);
                    }
                });
                //长按事件
                viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        onDuoclick.onLongClick(i);

                        return true;
                    }
                });




            }else if(viewHolder instanceof ViewHodlder2){
                //数据
                try {
                    JSONObject jsonObject = result.getJSONObject(i);
                    String title = jsonObject.getString("title");
                     //赋值
                    ((ViewHodlder2) viewHolder).text.setText(title);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onDuoclick.onclik(i);
                    }
                });


                viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        onDuoclick.onLongClick(i);

                        return true;
                    }
                });

            }
    }

    @Override
    public int getItemCount() {
        return result.length();
    }

    @Override
    public int getItemViewType(int position) {

        if(position%2==0){
            return TYPE_ONE;
        }else {
            return TYPE_TWO;
        }

    }
    //ViewHodlder
    class  ViewHodlder1 extends RecyclerView.ViewHolder{


        private final TextView text;
        private final ImageView img;

        public ViewHodlder1(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.tv);
            img = itemView.findViewById(R.id.img);
        }
    }

    class  ViewHodlder2 extends RecyclerView.ViewHolder{

        private final TextView text;
        public ViewHodlder2(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.tv);
        }
    }

    //接口回调
    public interface OnDuoclick{
        void onclik(int i);
        void onLongClick(int i);
    }

    private OnDuoclick onDuoclick;

    public void setOnDuoclick(OnDuoclick onDuoclick) {
        this.onDuoclick = onDuoclick;
    }




}











相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页