1. 程式人生 > >使用Recyclerview實現仿京東分類

使用Recyclerview實現仿京東分類

主佈局


​​​​
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <android.support.v7.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3.4"
        android:id="@+id/leftrecyclerview" />

    <android.support.v7.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="6.6"
        android:id="@+id/rightrecyclerview" />
</LinearLayout>

主體邏輯

 



public class ShopFragment extends Fragment {

    private View mView;
    private View view;
    private RecyclerView mLeftrecyclerview;
    private RecyclerView mRightrecyclerview;
    private LinearLayoutManager mLinearLayoutManager;
    private List<LeftTypeBean.DataBean> mDataBeans = new ArrayList<>();
    private MyLeftRecyclerViewAdapter mMyLeftRecyclerViewAdapter;
    private String LeftUrl = "http://www.zhaoapi.cn/product/getCatagory";
    private List<RightTypeBean.DataBean> mDataBeanList = new ArrayList<>();
    private MyRightTieleRecyclerViewAdapter mMyRightTieleRecyclerViewAdapter;
    private String RightUrl = "http://www.zhaoapi.cn/product/getProductCatagory?cid=";
    private LinearLayoutManager mLinearLayoutManager1;
    private MyRightRecyclerViewAdapter mMyRightRecyclerViewAdapter;

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化控制元件
        initView(mView);
        //初始化左側資料
        initLeftData();
        //初始化右側資料
        initRightData();

    }

    //初始化右側資料
    private void initRightData() {
        //佈局
        mLinearLayoutManager1 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mRightrecyclerview.setLayoutManager(mLinearLayoutManager1);
        //介面卡
        mMyRightTieleRecyclerViewAdapter = new MyRightTieleRecyclerViewAdapter(getActivity(), mDataBeanList);
        mRightrecyclerview.setAdapter(mMyRightTieleRecyclerViewAdapter);
        doData(1);
        mMyLeftRecyclerViewAdapter.setOnClickListener(new MyLeftRecyclerViewAdapter.onClickListener() {
            @Override
            public void onItemClick(int position) {
                int cid = mDataBeans.get(position).getCid();
                doData(cid);
                for (int i = 0; i < mDataBeans.size(); i++) {
                    if (position == i) {
                        mDataBeans.get(i).setClick(true);
                    } else {
                        mDataBeans.get(i).setClick(false);
                    }
                }
                mMyLeftRecyclerViewAdapter.notifyDataSetChanged();
            }
        });
    }

    //獲取右側 資訊
    private void doData(int cid) {
        new OkHttpUtil().OkHttpGet("http://www.zhaoapi.cn/product/getProductCatagory?cid=" + cid).setOkHttpListener(new OkHttpUtil.OkHttpListener() {
            @Override
            public void OkHttpSuccess(String data) {
                Gson gson = new Gson();
                mDataBeanList = gson.fromJson(data, RightTypeBean.class).getData();
                mMyRightTieleRecyclerViewAdapter.setList(mDataBeanList);
                mMyRightTieleRecyclerViewAdapter.notifyDataSetChanged();
            }

            @Override
            public void OkHttpError(String error) {

            }
        });
    }

    //初始化左側資料
    private void initLeftData() {
        //佈局
        mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mLeftrecyclerview.setLayoutManager(mLinearLayoutManager);
        //介面卡
        mMyLeftRecyclerViewAdapter = new MyLeftRecyclerViewAdapter(getActivity(), mDataBeans);
        mLeftrecyclerview.setAdapter(mMyLeftRecyclerViewAdapter);
        new OkHttpUtil().OkHttpGet(LeftUrl).setOkHttpListener(new OkHttpUtil.OkHttpListener() {
            @Override
            public void OkHttpSuccess(String data) {
                Gson gson = new Gson();
                mDataBeans = gson.fromJson(data, LeftTypeBean.class).getData();
                mDataBeans.get(0).setClick(true);//預設選中第一個
                mMyLeftRecyclerViewAdapter.update(mDataBeans);

            }

            @Override
            public void OkHttpError(String error) {

            }
        });
    }

    //初始化控制元件
    private void initView(View mView) {
        mLeftrecyclerview = (RecyclerView) mView.findViewById(R.id.leftrecyclerview);
        mRightrecyclerview = (RecyclerView) mView.findViewById(R.id.rightrecyclerview);
    }

}

左側Adapter

public class MyLeftRecyclerViewAdapter extends RecyclerView.Adapter<MyLeftRecyclerViewAdapter.MyViewHolder> {

    private Context mContext;
    private List<LeftTypeBean.DataBean> mDataBeans;

    public MyLeftRecyclerViewAdapter(Context context, List<LeftTypeBean.DataBean> dataBeans) {
        mContext = context;
        mDataBeans = dataBeans;
    }

    /**
     * 更新介面卡
     * @param dataBeans
     */
    public void update(List<LeftTypeBean.DataBean> dataBeans){
        mDataBeans = dataBeans;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.shop_left_recyclerview, viewGroup, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int i) {
        myViewHolder.mTextView.setText(mDataBeans.get(i).getName());
        //點選
        myViewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnClickListener.onItemClick(i);
                //點選改變顏色
                if (mDataBeans.get(i).isClick()){
                    myViewHolder.mLinearLayout.setBackgroundColor(Color.parseColor("#d43c3c"));
                    myViewHolder.mTextView.setTextColor(Color.parseColor("#FFFFFF"));
                }else {
                    myViewHolder.mLinearLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    myViewHolder.mTextView.setTextColor(Color.parseColor("#222222"));
                }
            }
        });
    }


    @Override
    public int getItemCount() {
        return mDataBeans == null ? 0 : mDataBeans.size();
    }

    //MyViewHolder
    class MyViewHolder extends RecyclerView.ViewHolder{
        RelativeLayout mLinearLayout;
        TextView mTextView;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            mTextView = itemView.findViewById(R.id.txt_left_name);
            mLinearLayout = itemView.findViewById(R.id.liner);
        }
    }



    private onClickListener mOnClickListener;

    public void setOnClickListener(onClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    /**
     * 點選事件
     */
    public interface onClickListener{
        void onItemClick(int position);
    }
}

 

左側佈局

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/liner"
    android:orientation="vertical">

        <TextView
            android:id="@+id/txt_left_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:gravity="center"
            android:text="XXXXX"
            android:textSize="24sp" />

</RelativeLayout>

右側佈局recyclerview鑲嵌

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


        <TextView
            android:layout_below="@id/c_imgicon"
            android:id="@+id/txt_right_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:gravity="center"
            android:text="XXXXX"
            android:textColor="#d61010"
            android:textSize="30sp" />
        <android.support.v7.widget.RecyclerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/recyclerview_title"/>

</LinearLayout>

右側Adapter

public class MyRightTieleRecyclerViewAdapter extends RecyclerView.Adapter<MyRightTieleRecyclerViewAdapter.MyViewHolder> {

    private Context mContext;
    private List<RightTypeBean.DataBean> mBeanList = new ArrayList<>();

    public MyRightTieleRecyclerViewAdapter(Context context, List<RightTypeBean.DataBean> beanList) {
        mContext = context;
        mBeanList = beanList;
    }

    public void setList(List<RightTypeBean.DataBean> beanList){
        mBeanList = beanList;
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.shop_right_title_recyclerview, viewGroup, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.mTextViewTitle.setText(mBeanList.get(i).getName());
        List<RightTypeBean.DataBean.ListBean> listBeans = mBeanList.get(i).getList();
        MyRightRecyclerViewAdapter adapter = new MyRightRecyclerViewAdapter(mContext, listBeans);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
        myViewHolder.mRecyclerView.setLayoutManager(gridLayoutManager);
        myViewHolder.mRecyclerView.setAdapter(adapter);
        adapter.setList(listBeans);
    }

    @Override
    public int getItemCount() {
        return mBeanList == null ? 0 : mBeanList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{
        RecyclerView mRecyclerView;
        TextView mTextViewTitle;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            mTextViewTitle = itemView.findViewById(R.id.txt_right_title);
            mRecyclerView = itemView.findViewById(R.id.recyclerview_title);
        }
    }
}

右側子佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher_round"
        android:layout_margin="3dp"
        android:id="@+id/c_imgicon"/>

    <TextView
        android:layout_below="@id/c_imgicon"
        android:id="@+id/txt_right_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:gravity="center"
        android:text="XXXXX"
        android:textColor="#999999"
        android:textSize="16sp" />

</LinearLayout>

右側子佈局的Adapter

public class MyRightRecyclerViewAdapter extends RecyclerView.Adapter<MyRightRecyclerViewAdapter.MyRightViewHolder> {

    private Context mContext;
    private List<RightTypeBean.DataBean.ListBean> mBeanLists = new ArrayList<>();

    public MyRightRecyclerViewAdapter(Context context, List<RightTypeBean.DataBean.ListBean> beanLists) {
        mContext = context;
        mBeanLists = beanLists;
    }

    public void setList(List<RightTypeBean.DataBean.ListBean> beanLists){
        mBeanLists = beanLists;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyRightViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.shop_right_recyclerview, null);
        MyRightViewHolder holder = new MyRightViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyRightViewHolder myRightViewHolder, final int i) {
        ImageLoader.getInstance().displayImage(mBeanLists.get(i).getIcon(),myRightViewHolder.mCircleImageView);
        myRightViewHolder.mTextViewName.setText(mBeanLists.get(i).getName());
        myRightViewHolder.mCircleImageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                Toast.makeText(mContext, mBeanLists.get(i).getName(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }


    @Override
    public int getItemCount() {
        return mBeanLists == null ? 0 : mBeanLists.size();
    }

    class MyRightViewHolder extends RecyclerView.ViewHolder {
        CircleImageView mCircleImageView;
        TextView mTextViewName;

        public MyRightViewHolder(@NonNull View itemView) {
            super(itemView);
            mCircleImageView = itemView.findViewById(R.id.c_imgicon);
            mTextViewName = itemView.findViewById(R.id.txt_right_name);
        }
    }
}

bean類

public class LeftTypeBean {
//左側bean類
    private String msg;
    private String code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
      

        private int cid;
        private String createtime;
        private String icon;
        private int ishome;
        private String name;

        private boolean isClick;

        public boolean isClick() {
            return isClick;
        }

        public void setClick(boolean click) {
            isClick = click;
        }

        public int getCid() {
            return cid;
        }

        public void setCid(int cid) {
            this.cid = cid;
        }

        public String getCreatetime() {
            return createtime;
        }

        public void setCreatetime(String createtime) {
            this.createtime = createtime;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public int getIshome() {
            return ishome;
        }

        public void setIshome(int ishome) {
            this.ishome = ishome;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

//右側bean類

public class RightTypeBean {

    private String msg;
    private String code;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
       

        private String cid;
        private String name;
        private String pcid;
        private List<ListBean> list;

        public String getCid() {
            return cid;
        }

        public void setCid(String cid) {
            this.cid = cid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPcid() {
            return pcid;
        }

        public void setPcid(String pcid) {
            this.pcid = pcid;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public static class ListBean {
           
            private String icon;
            private String name;
            private int pcid;
            private int pscid;

            public String getIcon() {
                return icon;
            }

            public void setIcon(String icon) {
                this.icon = icon;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public int getPcid() {
                return pcid;
            }

            public void setPcid(int pcid) {
                this.pcid = pcid;
            }

            public int getPscid() {
                return pscid;
            }

            public void setPscid(int pscid) {
                this.pscid = pscid;
            }
        }
    }
}

OKHttp

public class OkHttpUtil {

    private OkHttpListener mOkHttpListener;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0://成功
                    String data = (String) msg.obj;
                    mOkHttpListener.OkHttpSuccess(data);
                    break;
                case 1://失敗
                    String error = (String) msg.obj;
                    mOkHttpListener.OkHttpError(error);
                    break;
            }
        }
    };

    //生成    OkHttpListener  set方法
    public void setOkHttpListener(OkHttpListener okHttpListener) {
        mOkHttpListener = okHttpListener;
    }


    public OkHttpUtil OkHttpGet(String url){
        //獲取clench物件
        OkHttpClient okHttpClient = new OkHttpClient();
        //獲取Request物件
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            /**
             * 失敗回撥方法
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 1;
                message.obj = e.getMessage();
                mHandler.sendMessage(message);
            }

            /**
             * 成功回撥方法
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
               Message message = new Message();
               message.what = 0;
               message.obj = response.body().string();
               mHandler.sendMessage(message);
            }
        });
        return this;
    }


    public OkHttpUtil OkHttoPost(String url, FormBody formBody){
        //建立 clench 物件
        OkHttpClient okHttpClient = new OkHttpClient();
        //獲取Request
        Request request = new Request.Builder().url(url).post(formBody).build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            /**
             * 失敗回撥方法
             * @param call
             * @param e
             */
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 1;
                message.obj = e.getMessage();
                mHandler.sendMessage(message);
            }

            /**
             * 成功回撥方法
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = new Message();
                message.what = 0;
                message.obj = response.body().string();
                mHandler.sendMessage(message);
            }
        });
        return this;
    }

    //定義一個介面,進行回撥
    public interface OkHttpListener{
        //成功
        void OkHttpSuccess(String data);
        //失敗
        void OkHttpError(String error);

    }
}