Androdi之RecyclerView

原创 2016年06月04日 09:36:45

本文只是记录一些零碎的东西

RecyclerView API : https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

各路大神介绍RecyclerView 的文章很多了,只是本人浅浅的试用

使用很简单,在AndroidStudio的modulede里的build.gradle文件 dependencies 里新增引用

// recyclerview
    compile 'com.android.support:recyclerview-v7:23.0.+'
然后在布局文件里如下使用

<android.support.v7.widget.RecyclerView  
       android:id="@+id/id_recyclerview"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent"
       android:scrollbars="vertical"
       android:layout_above="@+id/linearLayout" />
MainActivity里几行代码造点数据就可以使用了

mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);

		//创建线性布局
		mLayoutManager = new LinearLayoutManager(this);
		//垂直方向  默认
		mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
		//横向
//        mLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
//		mRecyclerView.setLayoutManager(mLayoutManager);

还有新增和删除数据,贴上全部代码

每一条记录的布局,就是一个TextView

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

    <TextView
        android:id="@+id/id_num"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="1" />

</LinearLayout>
在res下的style里自定义下划线

<!--自定义下划线-->
        <item name= "android:listDivider">@drawable/my_divider </item >
drawable下的文件 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />
    <size android:height="4dp"/>

</shape>
MainActivity

import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/***
 * RecyclerView
 * 
 * @author chenling0418
 */
public class MainActivity extends AppCompatActivity {

	private RecyclerView mRecyclerView;
	private List<String> mDatas;
	private MyAdapter mAdapter;
	private LinearLayoutManager mLayoutManager; 

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

		initData();

		initView();

		initListener();
	}

	private void initView() {

		mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);

		//创建线性布局
		mLayoutManager = new LinearLayoutManager(this);
		//垂直方向  默认
		mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
		//横向
//        mLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
		/**给RecyclerView设置布局管理器
		 * LinearLayoutManager 现行管理器,支持横向、纵向。
		 * GridLayoutManager 网格布局管理器
		 * StaggeredGridLayoutManager 瀑布就式布局管理器
		 */
//		mRecyclerView.setLayoutManager(mLayoutManager);
		//GridLayoutManager(Context context,int spanCount) 每行显示item 个数
//		mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
		// StaggeredGridLayoutManager.HORIZONTAL  n 行,  下面的是有3列
		mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));

		//添加分割线,需要自己定义的继承自ItemDecoration的一个对象
//		mRecyclerView.addItemDecoration(new DividerItemDecoration(
//				this, DividerItemDecoration.HORIZONTAL_LIST));
		mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));


		//创建适配器
		mRecyclerView.setAdapter(mAdapter = new MyAdapter());
		//设置Item增加、移除动画
		mRecyclerView.setItemAnimator(new DefaultItemAnimator());


	}

	protected void initData() {
		mDatas = new ArrayList<String>();
		for (int i = 'A'; i < 'z'; i++) {
			mDatas.add("" + (char) i);
		}
	}

	private void initListener() {
		mAdapter.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onClick(int position) {
				Log.i("slack", "onClick:" + position + ":" + mDatas.get(position));
			}

			@Override
			public void onLongClick(int position) {
				Log.i("slack", "onLongClick:" + position + ":" + mDatas.get(position));
			}
		});
	}

	/**
	 * RecyclerView.Adapter
	 */
	class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

		// 点击监听事件
		private OnItemClickListener mOnItemClickListener;
		// 1. 视图创建,item显示
		@Override
		public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			// 这里 需要 android.support.v7.app 的 Activity
			MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
					MainActivity.this).inflate(R.layout.recycler_item, parent,
					false));
			return holder;
		}
		/* 2. 数据的绑定显示
		 * 如果是写出外部类,可以通过构造函数传递  mDatas 数据
		 */
		@Override
		public void onBindViewHolder(MyViewHolder holder,final int position) {
			holder.tv.setText(mDatas.get(position));

			if( mOnItemClickListener!= null){
				holder. itemView.setOnClickListener( new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						mOnItemClickListener.onClick(position);
					}
				});

				holder. itemView.setOnLongClickListener( new View.OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						mOnItemClickListener.onLongClick(position);
						return false;
					}
				});
			}
		}

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

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

			TextView tv;

			public MyViewHolder(View view) {
				super(view);
				tv = (TextView) view.findViewById(R.id.id_num);
			}
		}


		public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
			this. mOnItemClickListener = onItemClickListener;
		}

		public void addData(int position) {
			mDatas.add(position, "Insert One");
			notifyItemInserted(position);// 没有刷新,
		}

		public void removeData(int position) {
			mDatas.remove(position);
			notifyItemRemoved(position);
		}

	}

	public void add(View view){
		mAdapter.addData(0);
	}

	public void del(View view){
		mAdapter.removeData(0);
	}

}

interface OnItemClickListener{
	void onClick( int position);
	void onLongClick( int position);
}
DividerItemDecoration
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.State;
import android.util.Log;
import android.view.View;
/**
 * Created by chenling0418 on 2016/6/1.
 * copy from : http://blog.csdn.net/lmj623565791/article/details/45059587
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    // 采用系统主题(android.R.attr.listDivider)来设置成分隔线
    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };
    // 水平分割线
    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.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) {

        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }

    }


    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
            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);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}
DividerGridItemDecoration
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.RecyclerView.State;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
/**
 * Created by chenling0418 on 2016/6/1.
 */
public class DividerGridItemDecoration extends RecyclerView.ItemDecoration
{
    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };

    private Drawable mDivider;

        public DividerGridItemDecoration(Context context)
        {
            final TypedArray a = context.obtainStyledAttributes(ATTRS);
            mDivider = a.getDrawable(0);
            a.recycle();
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, State state)
        {

            drawHorizontal(c, parent);
            drawVertical(c, parent);

        }

        private int getSpanCount(RecyclerView parent)
        {
            // 列数
            int spanCount = -1;
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager)
            {

                spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
            } else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                spanCount = ((StaggeredGridLayoutManager) layoutManager)
                        .getSpanCount();
            }
            return spanCount;
        }

        public void drawHorizontal(Canvas c, RecyclerView parent)
        {
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++)
            {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                        .getLayoutParams();
                final int left = child.getLeft() - params.leftMargin;
                final int right = child.getRight() + params.rightMargin
                        + mDivider.getIntrinsicWidth();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }

        public void drawVertical(Canvas c, RecyclerView parent)
        {
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++)
            {
                final View child = parent.getChildAt(i);

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                        .getLayoutParams();
                final int top = child.getTop() - params.topMargin;
                final int bottom = child.getBottom() + params.bottomMargin;
                final int left = child.getRight() + params.rightMargin;
                final int right = left + mDivider.getIntrinsicWidth();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }

        private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
                                    int childCount)
        {
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager)
            {
                if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
                {
                    return true;
                }
            } else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                int orientation = ((StaggeredGridLayoutManager) layoutManager)
                        .getOrientation();
                if (orientation == StaggeredGridLayoutManager.VERTICAL)
                {
                    if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
                    {
                        return true;
                    }
                } else
                {
                    childCount = childCount - childCount % spanCount;
                    if (pos >= childCount)// 如果是最后一列,则不需要绘制右边
                        return true;
                }
            }
            return false;
        }

        private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
                                  int childCount)
        {
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager)
            {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一行,则不需要绘制底部
                    return true;
            } else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                int orientation = ((StaggeredGridLayoutManager) layoutManager)
                        .getOrientation();
                // StaggeredGridLayoutManager 且纵向滚动
                if (orientation == StaggeredGridLayoutManager.VERTICAL)
                {
                    childCount = childCount - childCount % spanCount;
                    // 如果是最后一行,则不需要绘制底部
                    if (pos >= childCount)
                        return true;
                } else
                // StaggeredGridLayoutManager 且横向滚动
                {
                    // 如果是最后一行,则不需要绘制底部
                    if ((pos + 1) % spanCount == 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public void getItemOffsets(Rect outRect, int itemPosition,
                                   RecyclerView parent)
        {
            int spanCount = getSpanCount(parent);
            int childCount = parent.getAdapter().getItemCount();
            if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,则不需要绘制底部
            {
                outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
            } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,则不需要绘制右边
            {
                outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
            } else
            {
                outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                        mDivider.getIntrinsicHeight());
            }
        }
}
对各位前辈表示感谢

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

androdi基础fragment

android3.0引入了fragment这个概念。它在一个活动中可以是用户界面或行为。下面我们就来一探究竟:      fragment生命周期      fragment和activity...

如何将系统app移植到Androdi Studio--Launcher2

在我门开发过程中,其实系统app有很多值得我们借鉴学习的地方。通过对系统app的了解,有助于我们进一步对android系统的了解,提高自我成长的有效途径。由于android系统的封装比较好,普通app...

Androdi Studio、Eclipdse用真机调试无法打印Log的解决办法

在使用真机调试时,我门会遇到部分机型打印不出来Log信息的情况,本博客就是为了解决这种情况来做一个简单的说明,我的机型是奇酷,虽然机型可能不同,但是导致的原因应该大致相同,希望看过本文后能给你解决问题...

androdi 数字验证码

自定义view,点击可以随机变换view上的数字,并且增加了干扰线,与干扰点。从而达到实现一个数字验证码功能,可通过getCode()方法来获取数字,并进行输入的判断

Androdi游戏开发

  • 2016-05-25 11:42
  • 11.13MB
  • 下载

androdi和php完美结合

  • 2013-11-11 10:40
  • 18.35MB
  • 下载

androdi开发生成pdf文件并显示

android开发中不能直接生成或打开pdf文件,我们这里需要借助第三方的类库itextpdf,导入以后添加依赖。 我们主要说一下怎么生成pdf文件,打开pdf文件可以用pdfview,网上有代码,...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)