Android之RecyclerView和ListView及LinearLayout列表的简单实现

   前言:

           在开始之前呢想必大家对列表都遇到很多各式不同的需求,具体看大家怎么习惯用哪个控件了

一:效果图:

二:实现步骤:

(A)RecyclerView控件

   我这呢用的SmartRefreshLayout+RecyclerView来实现的,因为需要分页加载,差不多都有注释就不用多解释什么了,直接上代码

1:引用刷新框架

//刷新框架
    implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.5'

2:layout布局

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/titlelayout" />

    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/fbrefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/view_id"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#fff"
        app:srlEnableLoadMoreWhenContentNotFull="false">

        <com.scwang.smartrefresh.layout.header.ClassicsHeader
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srlAccentColor="#393939" />

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

        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srlAccentColor="#393939" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>

</LinearLayout>

3:activity实现

(1):定义变量

    private SmartRefreshLayout fbrefresh;//刷新
    private int pageNum = 1;//页码
    private RecyclerView recyclerview;//列表
    private IncentiveActivitiesAdapter adapter;//adapter

(2):实例化

 /**
     * 实例化
     */
    private void instantiation() {
        relativefh = findViewById(R.id.relativefh);
        title = findViewById(R.id.title);
        title.setText("奖励活动");
        fbrefresh = findViewById(R.id.fbrefresh);
        //刷新
        fbrefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                rightDatelist();
            }
        });


        //加载
        fbrefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(final RefreshLayout refreshLayout) {
                pageNum++;
//                rightDatelist();
            }
        });
        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));//横向显示
        recyclerview.addItemDecoration(new SpacesItemDecoration(0));
        relativefh.setOnClickListener(this);
    }

(3):网络解析数据

  /**
     * 奖励活动列表 post 请求
     * (需要把参数放到request Body里面,并且在在header里面申明请求类型为“application/json”)
     */
    private void rightDatelist() {
        String url = NetConst.JLLB;
        System.out.println("====>>奖励活动列表url:" + url);
        JSONObject jsonObjectTemp = new JSONObject();
        try {
            jsonObjectTemp.put("appid", "com.hsrd.highlandwind");
            jsonObjectTemp.put("type", "1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String json = jsonObjectTemp.toString();
        System.out.println("奖励活动列表post传json:" + json);
        //获取网络工具类实例
        Okhttp3Utils netUtils = Okhttp3Utils.getInstance();
        netUtils.doPostJson(url, json, new Okhttp3Utils.MyNetCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                try {
                    String star = response.body().string();
                    System.out.println("===>>奖励活动列表获取成功:" + star);
                    /**把data下的数据转换成json对象**/
                    final JSONObject jDat = new JSONObject(star);
                    if (!jDat.getString("code").equals("0")) {
                        // 加载完数据之后,启动滑动
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                    if (jDat.getString("code").equals("0")) {
                        bean = (List<IncentiveBean>) JsonCllUtil.parseJsonToListint(jDat.getString("data"), new
                                TypeToken<List<IncentiveBean>>() {
                                }.getType());
                        // 加载完数据之后,启动滑动
                        Message msg = new Message();
                        if (pageNum == 1) {//1为刷新,3为加载
                            msg.what = 1;
                        } else {
                            msg.what = 3;
                        }
                        handler.sendMessage(msg);
                    } else {
                        // 加载完数据之后,启动滑动
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }

                } catch (Exception e) {
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                // 加载完数据之后,启动滑动
                Message msg = new Message();
                msg.what = 2;
                handler.sendMessage(msg);
            }
        });

    }

(4):得到数据赋值到adapter

 @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //刷新
                case 1:
                    adapter = new IncentiveActivitiesAdapter(bean, IncentiveActivities.this);
                    recyclerview.setAdapter(adapter);
                    fbrefresh.finishRefresh();
                    break;
                //加载
                case 3:
                    adapter.setData(bean);
                    fbrefresh.finishLoadMore();
                    break;

            }
        }
    };

4:adapter

package pinbidarider.hsrd.com.pinbidarider.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import pinbidarider.hsrd.com.pinbidarider.R;
import pinbidarider.hsrd.com.pinbidarider.activity.AwardDetails;
import pinbidarider.hsrd.com.pinbidarider.model.IncentiveBean;

/**
 * 作者:CaoLiulang
 * ❤
 * Date:2020/5/12
 * ❤
 * 模块:活动列表adapter
 */
public class IncentiveActivitiesAdapter extends RecyclerView.Adapter<IncentiveActivitiesAdapter.ViewHolder> {
    private List<IncentiveBean> list;
    private Context context;
    private IsetOnc isetonc;

    public IncentiveActivitiesAdapter(List<IncentiveBean> list, Context context) {
        this.list = list;
        this.context = context;
    }

    /**
     * 加载更多
     *
     * @param mPageList
     */
    public void setData(List<IncentiveBean> mPageList) {
        try {
            if (mPageList != null) {
                int previousSize = 0;
                try {
                    previousSize = list.size();
                } catch (Exception e) {
                    previousSize = 0;
                }
                int sizez = previousSize + 2;
                list.addAll(mPageList);
                notifyItemRangeInserted(sizez, mPageList.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.incentive_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    /**
     * 类似GetView
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        holder.textcdje.setText(list.get(position).name);//冲单金额
        holder.textkdje.setText("预计可得:¥" + list.get(position).money);//可得金额
        holder.texytgz.setText("奖励规则:" + list.get(position).remarks);//奖励规则
        //点击事件
        holder.relative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, AwardDetails.class).putExtra("id", list.get(position).id));
            }
        });
        //setTag当前的TAG
        holder.itemView.setTag(position);
    }

    /**
     * 长度
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return list.size();
    }

    /**
     * 初始化组件
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        TextView textcdje, textkdje, texytgz;
        RelativeLayout relative;

        public ViewHolder(final View itemView) {
            super(itemView);
            textcdje = itemView.findViewById(R.id.textcdje);
            textkdje = itemView.findViewById(R.id.textkdje);
            texytgz = itemView.findViewById(R.id.texytgz);
            relative = itemView.findViewById(R.id.relative);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isetonc != null) {
                        //点击id时候判断如果isetonc不为空的时候再给接口赋值,这样就不会出现空指针了
                        //获取之前setTag的值,给接口赋值
                        isetonc.setOnClickList((Integer) itemView.getTag());
                    }
                }
            });
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (isetonc != null) {
                        //点击id时候判断如果isetonc不为空的时候再给接口赋值,这样就不会出现空指针了
                        isetonc.setOnLongClickList((Integer) itemView.getTag());
                    }
                    return true;
                }
            });
        }
    }

    /**
     * 给接口赋值
     *
     * @param isetonc
     */
    public void setOnItem(IsetOnc isetonc) {
        this.isetonc = isetonc;
    }

    interface IsetOnc {
        //点击事件
        void setOnClickList(int xiabiao);

        //长按事件
        void setOnLongClickList(int xiabiao);
    }
}

(5):item布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/texttop"
        android:layout_width="match_parent"
        android:layout_height="10dp"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:layout_below="@+id/texttop"
        android:src="@mipmap/jlhdback" />

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/texttop"
        android:layout_margin="15dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/jlhdback"
            android:text="奖励活动"
            android:textColor="#ffffff"
            android:textSize="10dp" />

        <TextView
            android:id="@+id/textcdje"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="0元冲单奖励"
            android:textColor="#fff"
            android:textSize="16dp" />

        <TextView
            android:id="@+id/textkdje"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="预计可得¥0"
            android:textColor="#000"
            android:textSize="14dp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/linear"
        android:layout_marginLeft="3.5dp"
        android:layout_marginTop="-10dp"
        android:layout_marginRight="3.5dp"
        android:background="#fff">

        <TextView
            android:id="@+id/texytgz"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="10dp"
            android:layout_toLeftOf="@+id/image"
            android:text="奖励规则:。。。。。。。。。。。。"
            android:textSize="12dp" />

        <ImageView
            android:id="@+id/image"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="15dp"
            android:src="@mipmap/submit_address_right" />
    </RelativeLayout>
</RelativeLayout>

(B)ListView控件

1:layout布局

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/titlelayout" />

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:divider="#00000000"
        android:visibility="gone"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"/>

</LinearLayout>

2:activity(这是listview动态添加数据,我一般是后台数据没出来用这个看效果而已,都很少用listview了,都是用RecyclerView,item布局是上面那个item布局)

private ListView listview;
  //        //listview动态添加数据
//        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
//        for (int i = 1; i < 5; i++) {
//            HashMap<String, Object> map = new HashMap<String, Object>();
//            map.put("ItemTitle", i+"元冲单");
//            listItem.add(map);
//        }
//        //生成适配器的Item和动态数组对应的元素
//        SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,//数据源
//                R.layout.listview_itempw,
//                //动态数组与ImageItem对应的子项
//                new String[]{"ItemTitle"},
//                //ImageItem的XML文件里面的一个ImageView,两个TextView ID
//                new int[]{R.id.textsc}
//        );

//        //添加并且显示
//        listview_zy.setAdapter(listItemAdapter2);
//        listview_zy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                startActivity(new Intent(MessageCenter.this, NewsDetails.class));
//            }
//        });
//        setListViewHeightBasedOnChildren(listview_pw);

(C):LinearLayout控件

     有时候我们在详情页会遇到时间呀,价格呀这些列表,如果里面嵌套了ScollView,又有RecyclerView的话再嵌套listview就比较麻烦,所以直接用LinearLayout,看看效果图吧

1:layout布局直接添加一个LinearLayout

 <LinearLayout
      android:id="@+id/linearlist"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:orientation="vertical" />

2:activity使用

(1):定义

private LinearLayout linearlist,linearlist1;

(2):实例化

linearlist = findViewById(R.id.linearlist);
linearlist1 = findViewById(R.id.linearlist1);

(3):使用(使用前一定要清空一下)

  //清空View
       linearlist.removeAllViews();
       for (int i = 0; i < bean.holiday_condition.size(); i++) {
           LinearLayout flview = (LinearLayout) 
           LayoutInflater.from(AwardDetails.this).inflate(R.layout.biaoqian_tiem, null);
           final TextView textv = flview.findViewById(R.id.textv);
           textv.setText(bean.holiday_condition.get(i));
           linearlist.addView(flview);
           }
   //清空View
        linearlist1.removeAllViews();
          for (int i = 0; i < bean.time_condition.size(); i++) {
              LinearLayout flview = (LinearLayout) LayoutInflater.from(AwardDetails.this).inflate(R.layout.biaoqian_tiem, null);
              final TextView textv = flview.findViewById(R.id.textv);
              textv.setText(bean.time_condition.get(i));
              linearlist1.addView(flview);
              }

(4):Javabean

package pinbidarider.hsrd.com.pinbidarider.model;

import java.util.List;

/**
 * 作者:CaoLiulang
 * ❤
 * Date:2020/5/12
 * ❤
 * 模块:活动详情Javabean
 */
public class AwardDetailsBean {
    public String id;
    public String name;
    public String money;
    public String status;
    public String remarks;
    public String rider_condition;
    public String region_condition;
    public List<String> holiday_condition;
    public String industry_condition;
    public String store_condition;
    public List<String> time_condition;

    @Override
    public String toString() {
        return "AwardDetailsBean{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", money='" + money + '\'' +
                ", status='" + status + '\'' +
                ", remarks='" + remarks + '\'' +
                ", rider_condition='" + rider_condition + '\'' +
                ", region_condition='" + region_condition + '\'' +
                ", holiday_condition=" + holiday_condition +
                ", industry_condition='" + industry_condition + '\'' +
                ", store_condition='" + store_condition + '\'' +
                ", time_condition=" + time_condition +
                '}';
    }
}

 

 

 

---------------------到这就结束了,大神别喷,初学者可以借鉴,欢迎各位指出问题所在!

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叶已初秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值