欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MVP+登陆注册RecyclerView显示数据

程序员文章站 2022-04-18 17:21:04
...

废话不多话,直接上代码,有登陆,注册,RecyclerView线性布局显示数据 ,加载与刷新

MVP+登陆注册RecyclerView显示数据

Goodsbean 商品信息类

Loginbean登陆

RegBean注册


Model层

public interface IMainModel {
    public void postReg(String url, Map<String, String> params, OnNetListener<RegBean> onNetListener);
    public void PostLogin(String url, Map<String, String> params, OnNetListener<LoginBean> onNetListener);
    public void postGoods(String url, Map<String, Integer> params, OnNetListener<GoodsBean> onNetListener);
}
public class MainModel implements  IMainModel{
    private Handler handler = new Handler();
    /**
     * POST注册
     * @param url
     * @param params
     * @param onNetListener
     */
    @Override
    public void postReg(String url, Map<String, String> params, final OnNetListener<RegBean> onNetListener) {
        HttpUtils.getHttpUtils().doPost(url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              onNetListener.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final RegBean regBean = new Gson().fromJson(string, RegBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(regBean);
                    }
                });
            }
        });
    }
    /**
     * POST登陆
     * @param url
     * @param params
     * @param onNetListener
     */
    @Override
    public void PostLogin(String url, Map<String, String> params, final OnNetListener<LoginBean> onNetListener) {
        HttpUtils.getHttpUtils().doPost(url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onNetListener.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final LoginBean loginBean = new Gson().fromJson(string, LoginBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(loginBean);
                    }
                });
            }
        });
    }

    @Override
    public void postGoods(String url, Map<String, Integer> params, final OnNetListener<GoodsBean> onNetListener) {
        HttpUtils.getHttpUtils().doPostGoods(url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onNetListener.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final GoodsBean goodsBean = new Gson().fromJson(string, GoodsBean.class);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(goodsBean);
                    }
                });
            }
        });
    }
}


Net层

public interface Api {
    public static final String REGURL = "http://120.27.23.105/user/reg";
    public static final String LOGINURL = "http://120.27.23.105/user/login";
    public static final String SHOWURL = "http://120.27.23.105/product/getProducts";
}

public class HttpUtils {
    public static volatile HttpUtils httpUtils;
    public final OkHttpClient okHttpClient;

    public HttpUtils() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * 单例模式
     * @param
     * @return
     */

    public static HttpUtils getHttpUtils() {
        if (httpUtils == null) {
            synchronized (HttpUtils.class) {
                if (httpUtils == null) {
                    httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }

    /**
     * Get 请求
     */
    public void doGet(String url, Callback callback) {
        //创建一个Resquest
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * post请求
     */
    public void doPost(String url, Map<String, String> params, Callback callback) {
        //创建一个请求
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formbody = builder.build();
        Request request = new Request.Builder().url(url).post(formbody).build();
        okHttpClient.newCall(request).enqueue(callback);
    }
    /**
     * post请求获取商品
     */
    public void doPostGoods(String url, Map<String, Integer> params, Callback callback) {
        //创建一个请求
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Integer> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue()+"");
        }
        FormBody formbody = builder.build();
        Request request = new Request.Builder().url(url).post(formbody).build();
        okHttpClient.newCall(request).enqueue(callback);
    }
}
public interface OnNetListener<T> {

    public void onSuccess(T t);

    public void onFailure(Exception e);
}


p层

public class MainPresenter {
    private IMainModel iMainModel;
    private IMainActivity iMainActivity;
    private IRegActivity iRegActivity;
    private IUserActivity iUserActivity;
    public MainPresenter(IMainActivity iMainActivity) {
        this.iMainActivity = iMainActivity;
        iMainModel = new MainModel();
    }

    public MainPresenter(IRegActivity iRegActivity) {
        this.iRegActivity = iRegActivity;
        iMainModel = new MainModel();
    }

    public MainPresenter(IUserActivity iUserActivity) {
        this.iUserActivity = iUserActivity;
        iMainModel = new MainModel();
    }
    /**
     * PSOT注册
     */
    public void postReg(){
        HashMap<String, String> params = new HashMap<>();
        String phone = iRegActivity.getPhone();
        String pwd = iRegActivity.getPwd();
        boolean norm = isNorm(phone, pwd);
        if (!norm){
            return;
        }
        params.put("mobile", phone);
        params.put("password",pwd);
        iMainModel.postReg(Api.REGURL, params, new OnNetListener<RegBean>() {
            @Override
            public void onSuccess(RegBean regBean) {
                iRegActivity.goLogin(regBean);
            }

            @Override
            public void onFailure(Exception e) {
                iRegActivity.showErro(e);
            }
        });
    };

    /**
     * POST登陆
     */
    public void postLogin(){
        HashMap<String, String> params = new HashMap<>();
        String phone = iMainActivity.getPhone();
        String pwd = iMainActivity.getPwd();
        boolean norm = isNorm(phone, pwd);
        if (!norm){
            return;
        }
        params.put("mobile", phone);
        params.put("password",pwd);
        iMainModel.PostLogin(Api.LOGINURL, params, new OnNetListener<LoginBean>() {
            @Override
            public void onSuccess(LoginBean loginBean) {
                iMainActivity.goUser(loginBean);
            }

            @Override
            public void onFailure(Exception e) {
                iMainActivity.showErro(e);
            }
        });
    };

    /**
     * post获取商品数据
     */
    public void postGoods(int page){
        HashMap<String, Integer> params = new HashMap<>();
        params.put("pscid", 39);
        params.put("page",page);
        iMainModel.postGoods(Api.SHOWURL, params, new OnNetListener<GoodsBean>() {
            @Override
            public void onSuccess(GoodsBean goodsBean) {
                iUserActivity.showGoods(goodsBean);
            }

            @Override
            public void onFailure(Exception e) {
                iUserActivity.showErro(e);
            }
        });
    }
    /**
     * 本地校验手机号和密码
     * @param phone
     * @param pwd
     */
    private boolean isNorm(String phone, String pwd) {
        if (phone.length() < 1 || pwd.length() < 6){
            return false;
        }else {
            String num = "[1][358]\\d{9}";
            if (TextUtils.isEmpty(phone)) {
                return false;
            } else {
                return true;
            }
        }
    }
}

View层的接口

public interface IMainActivity {
    public String getPhone();
    public String getPwd();
    public void showErro(Exception e);
    public void goUser(LoginBean loginBean);
}
public interface IRegActivity {
    public String getPhone();
    public String getPwd();
    public void showErro(Exception e);
    public void goLogin(RegBean regBean);
}

public interface IUserActivity {
    public void showErro(Exception e);
    public void showGoods(GoodsBean goodsBean);
}

Mainactivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener, IMainActivity {
    /**
     * 请输入手机号
     */
    private EditText mEditphone;
    /**
     * 请输入密码
     */
    private EditText mEditpwd;
    /**
     * 注册
     */
    private Button mZc;
    /**
     * 登陆
     */
    private Button mLogin;
    private LinearLayout mActivityMain;
    private MainPresenter mainPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        mainPresenter = new MainPresenter(this);
    }

    private void initView() {
        mEditphone = (EditText) findViewById(R.id.editphone);
        mEditpwd = (EditText) findViewById(R.id.editpwd);
        mZc = (Button) findViewById(R.id.zc);
        mZc.setOnClickListener(this);
        mLogin = (Button) findViewById(R.id.login);
        mLogin.setOnClickListener(this);
        mActivityMain = (LinearLayout) findViewById(R.id.activity_main);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.zc:
                Intent intent = new Intent(MainActivity.this,RegActivity.class);
                startActivity(intent);
                break;
            case R.id.login:
                mainPresenter.postLogin();
                break;
        }
    }

    @Override
    public String getPhone() {
        return mEditphone.getText().toString().trim();
    }

    @Override
    public String getPwd() {
        return mEditpwd.getText().toString().trim();
    }

    @Override
    public void showErro(Exception e) {
        Toast.makeText(MainActivity.this,e+"", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void goUser(LoginBean loginBean) {
        if (loginBean.getCode().equals("0")){
            Intent intent = new Intent(MainActivity.this,UserActivity.class);
            startActivity(intent);
        }
        Toast.makeText(MainActivity.this,loginBean.getMsg(),Toast.LENGTH_SHORT).show();

    }


}

适配器

public class MyRVAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    private Context context;
    private List<GoodsBean.DataBean> list;

    public MyRVAdapter(Context context, List<GoodsBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.rv_item,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyViewHolder myViewHolder = (MyViewHolder) holder;
        GoodsBean.DataBean dataBean = list.get(position);
        String[] split = dataBean.getImages().split("\\|");
        Glide.with(context).load(split[0]).into(myViewHolder.iv);
        myViewHolder.title.setText(dataBean.getTitle());
        myViewHolder.pricelow.setText("原价:¥"+dataBean.getSalenum());
        myViewHolder.pricenew.setText("优惠价:¥"+dataBean.getPrice());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{

        private final ImageView iv;
        private final TextView title;
        private final TextView pricelow;
        private final TextView pricenew;

        public MyViewHolder(View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.rv_item_iv);
            title = itemView.findViewById(R.id.rv_item_tvTitle);
            pricelow = itemView.findViewById(R.id.rv_item_tvPricelow);
            pricelow.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            pricenew = itemView.findViewById(R.id.rv_item_tvPricenew);
        }
    }
}


注册

public class RegActivity extends AppCompatActivity implements View.OnClickListener,IRegActivity {
    /**
     * 请输入手机号
     */
    private EditText mEditphone;
    /**
     * 请输入密码
     */
    private EditText mEditpwd;
    /**
     * 注册
     */
    private Button mZc;
    private MainPresenter mainPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        initView();
        mainPresenter = new MainPresenter(this);
    }

    private void initView() {
        mEditphone = (EditText) findViewById(R.id.editphone);
        mEditpwd = (EditText) findViewById(R.id.editpwd);
        mZc = (Button) findViewById(R.id.zc);
        mZc.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.zc:
                mainPresenter.postReg();
                break;
        }
    }


    @Override
    public String getPhone() {
        return mEditphone.getText().toString().trim();
    }

    @Override
    public String getPwd() {
        return mEditpwd.getText().toString().trim();
    }

    @Override
    public void showErro(Exception e) {
        Toast.makeText(RegActivity.this,e+"", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void goLogin(RegBean regBean) {
        if (regBean.getCode().equals("0")){
            Intent intent = new Intent(RegActivity.this,MainActivity.class);
            startActivity(intent);
        }
        Toast.makeText(RegActivity.this,regBean.getMsg(),Toast.LENGTH_SHORT).show();
    }
}

public class UserActivity extends AppCompatActivity   implements IUserActivity {
    private RecyclerView mRv;
    private MainPresenter mainPresenter;
    private int page = 1;
    private List<GoodsBean.DataBean> list = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;
    private MyRVAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        initView();
        mainPresenter = new MainPresenter(this);
        mainPresenter.postGoods(page);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRv.setLayoutManager(manager);
        /**
         * 刷新
         */
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page =1;
                mainPresenter.postGoods(page);
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(UserActivity.this,"数据刷新完成!!!",Toast.LENGTH_SHORT).show();
            }
        });

        /**
         * 加载更多
         */
        mRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                // 这里在加入判断,判断是否滑动到底部
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LinearLayoutManager lm = (LinearLayoutManager) mRv.getLayoutManager();
                    if (lm.findLastVisibleItemPosition() == list.size() - 1) {
                        List<String> dataNew = new ArrayList<>();
                        page++;
                        mainPresenter.postGoods(page);
                        adapter.notifyDataSetChanged();
                        Toast.makeText(UserActivity.this, "数据加载完成!!!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    }

    @Override
    public void showErro(Exception e) {
        Toast.makeText(UserActivity.this, e + "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showGoods(GoodsBean goodsBean) {
        List<GoodsBean.DataBean> data = goodsBean.getData();
        if (data.size()==0){
            Toast.makeText(UserActivity.this,"没有可以加载的数据了!!!",Toast.LENGTH_SHORT).show();
            return;
        }
        list.addAll(data);
        adapter = new MyRVAdapter(this, list);
        mRv.setAdapter(adapter);
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="mvpframework.bwie.com.loginregistrectclerview.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陆"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="25sp"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="50dp"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="手机号:"
            android:textColor="@android:color/holo_blue_bright"
            android:textSize="16sp"
            android:textStyle="bold"
            />
        <EditText
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:hint="请输入手机号"
            android:id="@+id/editphone"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密码:"
            android:textColor="@android:color/holo_blue_bright"
            android:textSize="16sp"
            android:textStyle="bold"
            />
        <EditText
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:hint="请输入密码"
            android:id="@+id/editpwd"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="注册"
            android:id="@+id/zc"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登陆"
            android:id="@+id/login"/>
    </LinearLayout>
</LinearLayout>

reg.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_reg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  android:orientation="vertical"
    tools:context="mvpframework.bwie.com.loginregistrectclerview.RegActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="注册"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="25sp"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="50dp"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="手机号:"
            android:textColor="@android:color/holo_blue_bright"
            android:textSize="16sp"
            android:textStyle="bold"
            />
        <EditText
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:hint="请输入手机号"
            android:id="@+id/editphone"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="密码:"
            android:textColor="@android:color/holo_blue_bright"
            android:textSize="16sp"
            android:textStyle="bold"
            />
        <EditText
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:hint="请输入密码"
            android:id="@+id/editpwd"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="注册"
            android:id="@+id/zc"/>
    </LinearLayout>
</LinearLayout>

user

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  android:orientation="vertical"
    tools:context="mvpframework.bwie.com.loginregistrectclerview.UserActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="商品列表"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="20sp"
        android:layout_gravity="center"/>
    <android.support.v4.widget.SwipeRefreshLayout
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/swipeRefreshLayout">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v7.widget.RecyclerView>
    </android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>

rv_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="120dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center">
        <ImageView
            android:id="@+id/rv_item_iv"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:background="@mipmap/ic_launcher"/>
        <LinearLayout
            android:layout_weight="1"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:gravity="center_vertical"
                android:id="@+id/rv_item_tvTitle"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:text="我是商品的标题,超过两横,末尾用..."/>
            <TextView
                android:gravity="center_vertical"
                android:id="@+id/rv_item_tvPricelow"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:text="原价:¥199.99"/>
            <TextView
                android:gravity="center_vertical"
                android:id="@+id/rv_item_tvPricenew"
                android:layout_weight="1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:textColor="#ff3360"
                android:text="优惠价:¥99.99"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>