RecycleView加载布局和分割线

RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比listview更好。详细介绍看下面的链接

RecycleView详细介绍

首先加入依赖

    compile 'com.android.support:recyclerview-v7:26.1.0'

主页面和布局

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

    .support.v7.widget.RecyclerView>

主界面

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecy;
    List mList;

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

        /**
         * 注意两个方法执行先后顺序,先初始化数据再初始化视图,否则报空指针
         */
        initData();//初始化数据
        initView();//初始化view
    }

    private void initView() {
        // 初始化组件
        mRecy = findViewById(R.id.recyclerview);
        /**
         * 加载布局管理器(三种管理器)
         */
        // 1.线性布局管理器
        mRecy.setLayoutManager(new LinearLayoutManager(this));
        // 2.网格布局管理器
//        mRecy.setLayoutManager(new GridLayoutManager(this,3));
        // 3.流式布局管理器
//         mRecy.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));

        //添加自定义分割线
        mRecy.addItemDecoration(new MyDecoration(this, MyDecoration.VERTICAL_LIST));

        // 初始化适配器
        StudentListAdapter mStu = new StudentListAdapter(this, mList);
        mRecy.setAdapter(mStu);
    }

    private void initData() {
        mList = new ArrayList();
        for (int i = 0; i < 60; i++) {
            Student s = new Student();
            s.setUserName("我是第" + i + "个");
            mList.add(s);
        }
    }
}

模拟一个数据

public class Student {
    String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

适配器

public class StudentListAdapter extends RecyclerView.Adapter<StudentListAdapter.StudentViewHolder> {
    Context mContext;
    List mList;

    public StudentListAdapter(Context mcontext, List mlist) {
        this.mContext = mcontext;
        this.mList = mlist;
    }

    // 加载视图
    @Override
    public StudentViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        StudentViewHolder viewHolder = new StudentViewHolder(LayoutInflater.from(mContext)
                .inflate(R.layout.name_tv, parent, false));
        return viewHolder;
    }

    // 绑定视图
    @Override
    public void onBindViewHolder(StudentViewHolder holder, int position) {
        if (mList != null && mList.size() > 0) {
            Student student = mList.get(position);
            holder.name_tv.setText(student.getUserName());
        }
    }

    // 获取当前数据条目数量
    @Override
    public int getItemCount() {
        return mList.size();
    }

    // 自定义的ViewHolder,持有每个Item的的所有界面元素
    class StudentViewHolder extends RecyclerView.ViewHolder {

        private TextView name_tv;

        public StudentViewHolder(View itemView) {
            super(itemView);
            name_tv = (TextView) itemView.findViewById(R.id.name_tv);
        }
    }
}

子条目布局(name_tv)可以自己设置其他控件


<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:id="@+id/name_tv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:textSize="26sp" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher" />

LinearLayout>

添加RecycleView分割线

public class MyDecoration extends RecyclerView.ItemDecoration {

    private Context mContext;
    private Drawable mDivider;
    private int mOrientation;
    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    //我们通过获取系统属性中的listDivider来添加,在系统中的AppTheme中设置
    public static final int[] ATRRS = new int[]{
            android.R.attr.listDivider
    };

    public MyDecoration(Context context, int orientation) {
        this.mContext = context;
        final TypedArray ta = context.obtainStyledAttributes(ATRRS);
        this.mDivider = ta.getDrawable(0);
        ta.recycle();
        setOrientation(orientation);
    }

    //设置屏幕的方向
    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == HORIZONTAL_LIST) {
            drawVerticalLine(c, parent, state);
        } else {
            drawHorizontalLine(c, parent, state);
        }
    }

    //画横线, 这里的parent其实是显示在屏幕显示的这部分
    public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);

            //获得child的布局信息
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
            //Log.d("wnw", left + " " + top + " "+right+"   "+bottom+" "+i);
        }
    }

    //画竖线
    public void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int top = parent.getPaddingTop();
        int bottom = parent.getHeight() - parent.getPaddingBottom();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);

            //获得child的布局信息
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    //由于Divider也有长宽高,每一个Item需要向下或者向右偏移
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == HORIZONTAL_LIST) {
            //画横线,就是往下偏移一个分割线的高度
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            //画竖线,就是往右偏移一个分割线的宽度
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

你可能感兴趣的:(android进阶)