MVP登陆注册recycleview展示自定义搜索组合控件

 
 //登录
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;
    private HashMap<String,String> hash=new HashMap<>();

    @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.isPhoneLegal(phone);
                //1判断手机号是否正确
                if(mobileNO){
                    //判断密码
                    if(pwd.length()<3){
                        Toast.makeText(DengLu.this, "密码不对", Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                       //创建LoginPresenter
                        LoginPresenter loginPresenter=new LoginPresenter(this);
                        hash.put("phone",phone);
                        hash.put("pwd",pwd);
                        loginPresenter.send(hash);
                    }
                }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();
        }

    }
}
//loginpresent  
public class LoginPresenter {

    private final LoginModel loginModel;
    private final LoginView loginView;

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

    public void send(HashMap<String,String> hash) {
        loginModel.login(hash);
        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(HashMap<String,String> hash) {

       String url="http://172.17.8.100/small/user/v1/login";
        OkHttpUtils.getInstence().postData(url, hash, 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;
            }
        }
    };
}
//LoginView 
public interface LoginView {
    void view(String message);
}


//注册
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.isPhoneLegal(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);
}
//UI框架搭建(RadioBution+ViewPager+Fragment)
public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private RadioGroup rg;
    private ArrayList<Fragment> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1控件
        viewPager = findViewById(R.id.viewpage);
        rg = findViewById(R.id.rg);
        //2数据
        list = new ArrayList<>();
        Frag1 frag1 = new Frag1();
        Frag2 frag2 = new Frag2();
        Frag3 frag3 = new Frag3();
        list.add(frag1);
        list.add(frag2);
        list.add(frag3);
        //3适配器显示
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return list.get(i);
            }

            @Override
            public int getCount() {
                return list.size();
            }
        });
        //默认第一个按钮
        rg.check(R.id.rb1);

        //按钮设置pager页面动
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb1:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.rb2:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.rb3:
                        viewPager.setCurrentItem(2);
                        break;
                }
            }
        });




        //设置页面滑动监听 按钮也动
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                //改变按钮选中状态
                rg.check(rg.getChildAt(i).getId());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });



    }
}
//Frag1中自定义实现搜索功能和商品列表
public class Frag1 extends Fragment implements GoodsView,Serch.OnButtonClickListener{

    private Serch serch;
    private RecyclerView rlv;
    private String sou="板鞋";
    private GoodsPresenter goodsPresenter;
    private SwipyRefreshLayout srl;
    private Handler handler=new Handler();
    private int page=5;
    private List<GoodsJson.ResultBean> newlist;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag1, null, false);
       //找控件
        serch = view.findViewById(R.id.serch);
        srl = view.findViewById(R.id.srl);
        rlv = view.findViewById(R.id.rlv);
        //默认动画
        //rlv.setItemAnimator(new DefaultItemAnimator());

        //设置颜色
        srl.setColorSchemeColors(R.color.colorAccent,R.color.colorPrimary,R.color.colorPrimaryDark);
        //设置模式
        srl.setDirection(SwipyRefreshLayoutDirection.BOTH);
        //设置上拉下拉
        srl.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(int index) {
                //下拉刷新
                page=5;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        goodsPresenter.related(sou,page);
                        srl.setRefreshing(false);
                }
                },2000);

            }

            @Override
            public void onLoad(int index) {
                //上拉加载
                page++;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        goodsPresenter.related(sou,page);
                        srl.setRefreshing(false);
                    }
                },2000);
            }
        });
        //自带分割线
        rlv.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        //设置布局
        GridLayoutManager manager=new GridLayoutManager(getActivity(),2);
        rlv.setLayoutManager(manager);
        //创建GoodsPresenter
        goodsPresenter = new GoodsPresenter(this);
        goodsPresenter.related(sou,page);
        goodsPresenter.attachView(getActivity());

        //注册
        serch.setOnButtonClickListener(this);

        return  view;
    }

    @Override
    public void onResult(List<GoodsJson.ResultBean> list) {


        //适配器
        if(page==5){
            newlist = new ArrayList<GoodsJson.ResultBean>();
        }

        newlist.addAll(list);

        final MyRecyclerAdapter myRecyclerAdapter = new MyRecyclerAdapter(getActivity(), list);
        rlv.setAdapter(myRecyclerAdapter);

        myRecyclerAdapter.setOnMyLongRemoveListener(new MyRecyclerAdapter.OnMyLongRemoveListener() {
            @Override
            public void onItemClickLong(int i) {
                myRecyclerAdapter.onItemRemove(i);
                Toast.makeText(getActivity(), "删除成功"+i, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onClickItem(int i) {
                myRecyclerAdapter.addData(i);
                Toast.makeText(getActivity(), "添加成功"+i, Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public void onResult(String s) {
        Log.d("xxx",s);
        sou=s;
        Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
        goodsPresenter.related(sou,page);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        goodsPresenter.detchView();
        //activity销毁之前p先销毁
        Log.d("bbb","销毁了");
    }
}
//GoodsPresenter
public class GoodsPresenter<T>  {
    private final GoodsModel goodsModel;
    private final GoodsView goodsView;
    private Reference<T> reference;
    //有参构造


    public GoodsPresenter(GoodsView view) {
        //创建model
        goodsModel = new GoodsModel();

        goodsView = view;

    }

    public void attachView(T t) {
        //使用弱引用
        reference = new WeakReference<>(t);
    }


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

    //关联
    public void related(String sou,int page) {
        goodsModel.getData(sou,page);
        goodsModel.setOnGetGoodsListen(new GoodsModel.OnGetGoodsListen() {
            @Override
            public void onResult(List<GoodsJson.ResultBean> list) {
                //传递数据接口
                 goodsView.onResult(list);
            }
        });
    }
}
//GoodsModel 
public class GoodsModel {

    //接口回调
    public interface OnGetGoodsListen{
        void onResult(List<GoodsJson.ResultBean> list);
    }

    private OnGetGoodsListen onGetGoodsListen;

    public void setOnGetGoodsListen(OnGetGoodsListen onGetGoodsListen) {
        this.onGetGoodsListen = onGetGoodsListen;
    }

    public void getData(String sou,int page) {
        String path="http://172.17.8.100/small/commodity/v1/findCommodityByKeyword?keyword="+sou+"&page=1&count="+page;
        //引用网络工具类
        OkHttpUtils.getInstence().getData(path, 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();
                //Handler
                Message message = new Message();
                message.what=0;
                message.obj=string;
                handler.sendMessage(message);
            }
        });


    }


    //handler接受消息
    @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;
                    Gson gson = new Gson();
                    GoodsJson goodsJson = gson.fromJson(obj, GoodsJson.class);
                    List<GoodsJson.ResultBean> result = goodsJson.getResult();
                    Log.d("xxx",result.toString());
                    if(onGetGoodsListen!=null){
                        onGetGoodsListen.onResult(result);
                    }

                    break;
            }
        }
    };

}
//GoodsView 
public interface GoodsView {
    void onResult(List<GoodsJson.ResultBean> list);
}

//OK网络请求工具类
public class OkHttpUtils {
    //声明
    private static OkHttpUtils okHttpUtils = null;

    public OkHttpUtils() {
    }

    //返回实例的方法
    public static OkHttpUtils getInstence() {
        if (okHttpUtils == null) {
            synchronized (OkHttpUtils.class) {
                okHttpUtils = new OkHttpUtils();
            }
        }
        return okHttpUtils;
    }

    //创建Okshi
    private static OkHttpClient okHttpClient = null;

    public static synchronized OkHttpClient getOkHttpClient() {
        //拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("aaa", message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    //添加日志拦截器
                    .addInterceptor(httpLoggingInterceptor).build();
        }
        return okHttpClient;
    }


    //get请求数据
    public static void getData(String url,Callback callback) {
        //得到ok对象
        OkHttpClient okHttpClient = getOkHttpClient();
        //得到请求
        Request request = new Request.Builder().url(url).build();
        //请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }


    //post请求数据
    public static void postData(String url, Map<String,String> params, Callback callback) {
        //1得到ok对象
        OkHttpClient okHttpClient = getOkHttpClient();
        //2得到请求体
        FormBody.Builder builder=new FormBody.Builder();
        //遍历集合
        for (String key:params.keySet()){
            builder.add(key,params.get(key));
        }
        FormBody formBody= builder.build();
       //3得到请求
        Request request = new Request.Builder().post(formBody).url(url).build();
        //请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }


}
//正则验证手机号工具类
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;
    }*/


    /**
     * 大陆号码或香港号码均可
     */
    public static boolean isPhoneLegal(String str)throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
     * 此方法中前三位格式有:
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数,5|6|8|9开头+7位任意数
     */
    public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException {
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }



}
//自定义组合搜索 
public class Serch extends LinearLayout implements View.OnClickListener,TextWatcher {

    private Button bt1;
    private Button bt2;
    private EditText et;
    //接口回调
    public interface OnButtonClickListener{
        void onResult(String s);
    }

    private OnButtonClickListener onButtonClickListener;

    public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) {
        this.onButtonClickListener = onButtonClickListener;
    }

    public Serch(Context context) {
        super(context);
    }

    public Serch(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获得布局
        LayoutInflater.from(context).inflate(R.layout.serch,this,true);
        bt1 = findViewById(R.id.bt1);
        bt2 = findViewById(R.id.bt2);
        et = findViewById(R.id.et);
        //点击事件
        bt1.setOnClickListener(this);
        bt2.setOnClickListener(this);
        //addchangelistener放啊发
      //  et.addTextChangedListener(this);
    }

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


    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.bt2:
                //获取输入框的值
                String s = et.getText().toString();
                if(s.equals("")){
                    Toast.makeText(getContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                }else{
                    //接口回调
                    if(onButtonClickListener!=null){
                        onButtonClickListener.onResult(s);
                    }
                }

                break;

        }

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String s1 = et.getText().toString();

    }


}
//自定义组合的xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/bt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/aa"
            />

        <EditText
            android:id="@+id/et"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />

        <Button
            android:id="@+id/bt2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:text="搜索"
            android:background="#fff"
            />



    </LinearLayout>



</LinearLayout>
//自定义属性实现登录注册标题栏
//创建attrs.xml文件
<resources>
    <declare-styleable name="loign_top">
        <attr name="login_text"  format="string"/>
        <attr name="login_color" format="color"/>

    </declare-styleable>

    <declare-styleable name="reg_top">
        <attr name="reg_text"  format="string"/>
        <attr name="reg_color" format="color"/>

    </declare-styleable>




</resources>
//Login_Top 
public class Login_Top extends TextView {


    public Login_Top(Context context) {
        super(context);
    }

    public Login_Top(Context context,  AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }



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

    private void init(Context context, AttributeSet attrs) {
        if (attrs!=null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.loign_top);
            String login_text = typedArray.getString(R.styleable.loign_top_login_text);
            int color = typedArray.getColor(0, R.styleable.loign_top_login_color);
            setText(login_text);
            setTextColor(color);

        }
     }
}
//登录标题栏的自定义控件
<crq.bwie.com.week2_2_1.customer.Login_Top
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:login_text="登录"
        app:login_color="#ccc"
        android:textSize="30dp"
        android:gravity="center"
        />
//Reg_Top 
public class Reg_Top extends TextView {


    public Reg_Top(Context context) {
        super(context);
    }

    public Reg_Top(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }



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

    private void init(Context context, AttributeSet attrs) {
        if (attrs!=null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.reg_top);
            String login_text = typedArray.getString(R.styleable.reg_top_reg_text);
            int color = typedArray.getColor(0, R.styleable.reg_top_reg_color);
            setText(login_text);
            setTextColor(color);

        }






    }


}
//注册标题栏的自定义控件
 <crq.bwie.com.week2_2_1.customer.Reg_Top
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:reg_text="注册"
        app:reg_color="#0f0"
        android:textSize="30dp"
        android:gravity="center"
        />
//recycleview 的适配器
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewhodler> {

    private Context context;
    private List<GoodsJson.ResultBean> list;

    public MyRecyclerAdapter(Context context, List<GoodsJson.ResultBean> list) {
        this.context=context;
        this.list=list;
    }


    @NonNull
    @Override
    public MyViewhodler onCreateViewHolder(@NonNull ViewGroup viewGroup, final int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.item, null, false);
        final MyViewhodler myViewhodler = new MyViewhodler(view);
        //设置点击事件
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onMyLongRemoveListener!=null){
                    int layoutPosition = myViewhodler.getLayoutPosition();
                    onMyLongRemoveListener.onClickItem(layoutPosition);
                }
            }
        });

        //设置长按点击事件
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(onMyLongRemoveListener!=null){
                    int layoutPosition = myViewhodler.getLayoutPosition();
                    onMyLongRemoveListener.onItemClickLong(layoutPosition);
                }

                return true;
            }
        });

        return myViewhodler;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewhodler myViewhodler, int i) {
        String name = list.get(i).getCommodityName();
        int price = list.get(i).getPrice();
        //数据
        Glide.with(context).load(list.get(i).getMasterPic()).into(myViewhodler.img);
        myViewhodler.title.setText(name);
        myViewhodler.price.setText(price+"");

    }


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

    class MyViewhodler extends RecyclerView.ViewHolder {


        private final ImageView img;
        private final TextView title;
        private final TextView price;

        public MyViewhodler(@NonNull View itemView) {
            super(itemView);

            img = itemView.findViewById(R.id.img);
            title = itemView.findViewById(R.id.title);
            price = itemView.findViewById(R.id.price);


        }
    }

    //接口回调
    public interface  OnMyLongRemoveListener{
        void onItemClickLong(int i);
        void onClickItem(int i);
    }

    private OnMyLongRemoveListener onMyLongRemoveListener;

    public void setOnMyLongRemoveListener(OnMyLongRemoveListener onMyLongRemoveListener) {
        this.onMyLongRemoveListener = onMyLongRemoveListener;
    }

    public void addData(int position) {
//      在list中添加数据,并通知条目加入一条
        GoodsJson.ResultBean resultBean = new GoodsJson.ResultBean();
        resultBean.setCommodityName("暗示法大使馆");
        list.add(position,resultBean);
      notifyItemInserted(position);
    }



    //点击条目删除数据 刷新
    public void onItemRemove(int i){
        list.remove(i);
        notifyDataSetChanged();
    };
}

















 
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值