MVP实现登录注册+RecyclerView展示数据+自定义view

MVP实现登录注册+RecyclerView展示数据+自定义view

搭建框架

<?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=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />
    <RadioGroup
        android:id="@+id/radio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/b1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="首页"
            android:drawableTop="@drawable/selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"/>
        <RadioButton
            android:id="@+id/b2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="分类"
            android:drawableTop="@drawable/selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"/>
        <RadioButton
            android:id="@+id/b3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="订单"
            android:drawableTop="@drawable/selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"/>
        <RadioButton
            android:id="@+id/b4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="我的"
            android:drawableTop="@drawable/selector"
            android:button="@null"
            android:gravity="center"
            android:padding="5dp"/>
    </RadioGroup>

</LinearLayout>
public class MainActivity extends FragmentActivity {

    private ViewPager pager;
    private RadioGroup radioGroup;
    private ArrayList<Fragment> arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pager = findViewById(R.id.pager);
        radioGroup = findViewById(R.id.radio);

        arrayList = new ArrayList<Fragment>();
        arrayList.add(new Frag_01());
        arrayList.add(new Frag_02());
        arrayList.add(new Frag_03());
        arrayList.add(new Frag_04());
        radioGroup.check(radioGroup.getChildAt(0).getId());
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return arrayList.get(i);
            }

            @Override
            public int getCount() {
                return arrayList.size();
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.b1:
                        pager.setCurrentItem(0);
                        break;
                    case R.id.b2:
                        pager.setCurrentItem(1);
                        break;
                    case R.id.b3:
                        pager.setCurrentItem(2);
                        break;
                    case R.id.b4:
                        pager.setCurrentItem(3);
                        break;
                }
            }
        });
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                radioGroup.check(radioGroup.getChildAt(i).getId());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }
}

自定义view

<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=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/button"
            android:text="三"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/exid"
            android:layout_width="350dp"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/button2"
            android:text="搜索"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

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

</LinearLayout>
public class CustoView_show extends RelativeLayout {
    public CustoView_show(Context context) {
        super(context);
    }

    public CustoView_show(Context context, AttributeSet attrs) {
        super(context, attrs);
        getData(context);
    }


    public CustoView_show(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    private void getData(final Context context) {
        View view=LayoutInflater.from(context).inflate(R.layout.cus_view,null,false);
        addView(view);
    }
}

实现frag_01

<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=".MainActivity">

    <zk2_lx.bw.com.zk2_lx.widget.CustoView_show
        android:id="@+id/cus"
        android:layout_width="match_parent"
        android:layout_height="50dp"></zk2_lx.bw.com.zk2_lx.widget.CustoView_show>

    <com.bawei.swiperefreshlayoutlibrary.SwipyRefreshLayout
        android:id="@+id/sw"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rcy"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
    </com.bawei.swiperefreshlayoutlibrary.SwipyRefreshLayout>

</LinearLayout>
public class Frag_01 extends Fragment implements ShowView {

    private RecyclerView recyclerView;
    private CustoView_show custoView_show;
    private SwipyRefreshLayout swipyRefreshLayout;
    private String title="鞋";
    private int page=1;
    private EditText editText;
    private Button button;
    private ShowPresenter showPresenter;
    private Handler handler=new Handler();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.frag_01,container,false);

        button = view.findViewById(R.id.button2);
        editText = view.findViewById(R.id.exid);
        recyclerView = view.findViewById(R.id.rcy);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(getContext(),2);
        recyclerView.setLayoutManager(gridLayoutManager);

          showPresenter= new ShowPresenter(this);

        showPresenter.onRelated(title,page);
       

        initData();
        swipyRefreshLayout = view.findViewById(R.id.sw);
        //设置颜色
        swipyRefreshLayout.setColorSchemeColors(R.color.colorAccent,R.color.colorPrimary,R.color.colorPrimaryDark);;
        //设置模式
        swipyRefreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTH);
        //设置sw监听
        swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(int index) {
                //下拉刷新
                page=1;
                showPresenter.onRelated(title,page);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "刷新成功", Toast.LENGTH_SHORT).show();
                        swipyRefreshLayout.setRefreshing(false);
                    }
                },2000);
            }

            @Override
            public void onLoad(int index) {
                //上拉加载
                page++;
                showPresenter.onRelated(title,page);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(), "加载成功", Toast.LENGTH_SHORT).show();
                        swipyRefreshLayout.setRefreshing(false);
                    }
                },2000);
            }
        });
        return view;
    }

    @Override
    public void getViewData(String json) {
        if (json!=null){
            Gson gson=new Gson();
            JsonBean jsonBean = gson.fromJson(json, JsonBean.class);
            List<JsonBean.ResultBean> result = jsonBean.getResult();
            final MyAdapter adapter=new MyAdapter(getContext(),result);
            recyclerView.setAdapter(adapter);

            adapter.setOnRecyclerViewItemLongClickLisenter(new MyAdapter.OnRecyclerViewItemLongClickLisenter() {
                @Override
                public void onRecyclerViewItemLongClick(int position) {
                    Toast.makeText(getActivity(), "长按条目:\" + position", Toast.LENGTH_SHORT).show();
                    adapter.removeItem(position);
                }
            });
        }
    }

    private void initData() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title=editText.getText().toString();
                if (title.isEmpty()){
                    Toast.makeText(getActivity(), "请输入要搜索的内容", Toast.LENGTH_SHORT).show();
                }else {
                    showPresenter.onRelated(title,page);
                }
            }
        });
    }
}

public class ShowPresenter<T> {

    private final ShowModel showModel;
    private final ShowView showView;
    private Reference<T> tReference;
    public ShowPresenter(ShowView view) {
        showModel = new ShowModel();
        showView = view;
    }

    public void attachView(T t){
        tReference=new WeakReference<T>(t);
    }


    public void deatchView(){
        if (tReference!=null){
            tReference.clear();
            tReference=null;
        }
    }



    public void onRelated(String title, int page) {
        showModel.getHttpData(title,page);
        showModel.setOnShowListener(new ShowModel.onShowListener() {
            @Override
            public void onResult(String json) {
                showView.getViewData(json);
            }
        });
    }
}

public class ShowModel {

    private String url = "http://172.17.8.100/small/commodity/v1/findCommodityByKeyword?keyword=";
    private String path = "&count=10&page=";
    private String xie = "";
    private String page1 = "";

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String json= (String) msg.obj;
                   onShowListener.onResult(json);
                    break;
            }
        }
    };





    public void getHttpData(String title, int page) {
        xie = title;
        page1 = page+"";
        OkHttpUtils.getInstance().doGet(url+xie+path+page1, 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();
//                Log.i("jjj",json);
                Message message  =new Message();
                message.what = 0;
                message.obj = json;
                handler.sendMessage(message);
            }
        });
    }

    public interface onShowListener{
        void onResult(String json);
    }

    public onShowListener onShowListener;

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

public interface ShowView {
    void getViewData(String json);
}

适配器

<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=".MainActivity">

    <ImageView
        android:id="@+id/img"
        android:layout_width="220dp"
        android:layout_height="220dp"
        android:layout_alignParentRight="true"/>

    <TextView
        android:id="@+id/title1"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/img"
        android:text="哈哈" />


</LinearLayout>
public class MyAdapter extends  RecyclerView.Adapter<MyAdapter.ViewHolder>{
    private Context context;
    private List<JsonBean.ResultBean> result=new ArrayList<>();
    private static final int TYPE_ONE = 0;
    private static final int TYPE_TWO = 1;

    public interface OnRecyclerViewItemLongClickLisenter {
        void onRecyclerViewItemLongClick(int position);
    }

    private OnRecyclerViewItemLongClickLisenter longClickLisenter;

    public void setOnRecyclerViewItemLongClickLisenter(OnRecyclerViewItemLongClickLisenter longClickLisenter) {
        this.longClickLisenter = longClickLisenter;
    }



    public MyAdapter(Context context, List<JsonBean.ResultBean> result) {
        this.context = context;
        this.result = result;
    }



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

            //添加点击事件
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //获取view对应的位置
                    int position=viewHolder.getLayoutPosition();
                    if (longClickLisenter!=null){
                        //回调监听
                        longClickLisenter.onRecyclerViewItemLongClick(position);
                    }
                    return true;
                }
            });
            return viewHolder;
        }else {
            View view=LayoutInflater.from(viewGroup.getContext()).inflate(android.R.layout.simple_expandable_list_item_1,null,false);
            ViewHolder viewHolder=new ViewHolder(view);
            return viewHolder;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        int itemViewType=getItemViewType(i);
        if (TYPE_ONE==itemViewType){
            viewHolder.title.setText(result.get(i).getCommodityName());
            Glide.with(context).load(result.get(i).getMasterPic()).into(viewHolder.img);
        }else {
            viewHolder.title2.setText(result.get(i).getCommodityName());
        }
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private final ImageView img;
        private final TextView title;
        private final TextView title2;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title1);
            title2 = itemView.findViewById(android.R.id.text1);
            img = itemView.findViewById(R.id.img);
        }
    }

    public void removeItem(int position){
        result.remove(position);
        notifyDataSetChanged();
    }
}

封装工具类

public class Utils {
    public static boolean isMobileNO(String mobileNums) {
        /**
         * 判断字符串是否符合手机号码格式
         * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
         * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
         * 电信号段: 133,149,153,170,173,177,180,181,189
         * @param str
         * @return 待检测的字符串
         */
        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表下一位为数字可以是几,"[0-9]"代表可以为0-9中的一个,"[5,7,9]"表示可以是5,7,9中的任意一位,[^4]表示除4以外的任何一个,\\d{9}"代表后面是可以是0~9的数字,有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }
}
public class OkHttpUtils {
    private OkHttpUtils() {};

    private static OkHttpUtils okHttpUtils=null;

    public static OkHttpUtils getInstance(){
        if (okHttpUtils==null){
            okHttpUtils=new OkHttpUtils();
        }
        return okHttpUtils;
    }

    //拦截器
    private static Interceptor myInterceptor(){
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("xx",message);
            }
        });
        return interceptor;
    }

    public static void doGet(String url, Callback callback){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(myInterceptor())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }



    public static void doPost(String url, Map<String,String> params, Callback callback){
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(myInterceptor())
                .build();
        //请求体
        FormBody.Builder builder = new FormBody.Builder();
        //遍历map集合
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(callback);
    }
}

实现frag_04

<RelativeLayout 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=".MainActivity">

    <ImageView
        android:id="@+id/img"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_launcher_background"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
public class Frag_04 extends Fragment {

    private ImageView imageView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.frag_04,container,false);

        imageView = view.findViewById(R.id.img);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(),LoginActivity.class));
            }
        });
        return view;
    }
}

登录

<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=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:text="登录"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_phone"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="50dp"
        android:hint="请输入手机号" />

    <EditText
        android:id="@+id/et_pwd"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="50dp"

        android:layout_marginRight="50dp"
        android:hint="请输入密码" />

    <Button
        android:id="@+id/bt_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:text="登录" />
    <Button
        android:id="@+id/bt_zc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="注册" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
public class LoginActivity extends AppCompatActivity implements LoginView {


    private EditText et_phone;
    private EditText et_pwd;
    private Button login;
    private Button zc;
    private LoginPresenter loginPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        et_phone = findViewById(R.id.et_phone);
        et_pwd = findViewById(R.id.et_pwd);
        login = findViewById(R.id.bt_login);
        zc = findViewById(R.id.bt_zc);

        loginPresenter = new LoginPresenter(this);


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = et_phone.getText().toString();
                String pwd = et_pwd.getText().toString();
                boolean mobileNO = Utils.isMobileNO(phone);
                if (!mobileNO){
                    Toast.makeText(LoginActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (pwd.length()<3){
                    Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String,String> params=new HashMap<>();
                params.put("phone",phone);
                params.put("pwd",pwd);
                loginPresenter.sendParamter(params);
            }
        });


        zc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this,ZcActivity.class));
                finish();
            }
        });
    }

    @Override
    public void getViewData(String status) {
        if (status.equals("0000")){
            startActivity(new Intent(LoginActivity.this,MainActivity.class));
            finish();
        }
    }
}

public class LoginPresenter {

    private final LoginModel loginModel;
    private final LoginView loginView;

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

    public void sendParamter(Map<String,String> params) {
        loginModel.getHttpData(params);
        loginModel.setLoginListener(new LoginModel.onLoginListener() {
            @Override
            public void onResult(String status) {
                loginView.getViewData(status);
            }
        });
    }
}

public class LoginModel {
    private String path="http://172.17.8.100/small/user/v1/login";

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String json= (String) msg.obj;
                    Log.i("xxx",json);
                    try {
                        JSONObject jsonObject=new JSONObject(json);
                        String status = jsonObject.getString("status");
                        loginListener.onResult(status);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getHttpData(Map<String,String> params) {
        OkHttpUtils.doPost(path, params, 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);
            }
        });
    }
    public interface onLoginListener{
        void onResult(String status);
    }
    public onLoginListener loginListener;

    public void setLoginListener(onLoginListener loginListener) {
        this.loginListener = loginListener;
    }
}

public interface LoginView {
    void getViewData(String status);
}

注册

<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=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#621afc">

        <TextView
            android:id="@+id/return_regist"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:text="<"
            android:textColor="#faf8f8"
            android:textSize="30sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:text="注册"
            android:textColor="#faf8f8"
            android:textSize="30sp" />
    </RelativeLayout>


    <EditText
        android:id="@+id/num_regist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="30dp"
        android:hint="手机号"
        android:padding="10dp" />

    <EditText
        android:id="@+id/pwd_regist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:hint="密码"
        android:padding="10dp" />


    <Button
        android:id="@+id/regist_regist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="立即注册" />
</LinearLayout>
public class ZcActivity extends AppCompatActivity implements ZcView {


    private EditText num_regist;
    private EditText pwd_regist;
    private Button button;
    private TextView textView;
    private final ZcPresenter zcPresenter = new ZcPresenter(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zc);
        num_regist = findViewById(R.id.num_regist);
        pwd_regist = findViewById(R.id.pwd_regist);
        button = findViewById(R.id.regist_regist);
        textView = findViewById(R.id.return_regist);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ZcActivity.this,LoginActivity.class));
                finish();
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = num_regist.getText().toString();
                String pwd = pwd_regist.getText().toString();
                boolean mobileNO = Utils.isMobileNO(phone);
                if (!mobileNO){
                    Toast.makeText(ZcActivity.this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                }
                if (pwd.length()<3){
                    Toast.makeText(ZcActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                }
                HashMap<String,String> params=new HashMap<>();
                params.put("phone",phone);
                params.put("pwd",pwd);
                zcPresenter.sendParameter(params);
            }
        });
    }

    @Override
    public void getViewData(String status) {
        if (status.equals("0000")){
            startActivity(new Intent(ZcActivity.this,MainActivity.class));
            finish();
        }
    }
}

public class ZcPresenter {

    private final ZcModel zcModel;
    private final ZcView zcView;


    public ZcPresenter(ZcView view) {
         zcModel= new ZcModel();
         zcView=view;
    }

    public void sendParameter(HashMap<String,String> params) {
        zcModel.getHttpData(params);
        zcModel.setRegistListener(new ZcModel.onRegistListener() {
            @Override
            public void onResult(String status) {
                zcView.getViewData(status);
            }
        });
    }
}

public class ZcModel {
    String url = "http://172.17.8.100/small/user/v1/register";
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String json= (String) msg.obj;
                    try {
                        JSONObject jsonObject=new JSONObject(json);
                        String status = jsonObject.getString("status");
                        registListener.onResult(status);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getHttpData(HashMap<String,String> params) {
        OkHttpUtils.doPost(url, params, 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);
            }
        });
    }
    public interface onRegistListener{
        void onResult(String status);
    }

    public onRegistListener registListener;

    public void setRegistListener(onRegistListener registListener) {
        this.registListener = registListener;
    }
}

public interface ZcView {
    void getViewData(String status);
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值