Android控件大全(三)——RecyclerView

是时候用RecyclerView来替换ListView和GridView了

好处就不多说了,百度一搜一大把,来介绍下用法

先定义个适配器:

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

    private  Context context;
    private  String[] datas;
    private  int [] icons;
    private  OnItemClickListener mListener;
    public  BottomSheetAdapter(Context context,String[] datas,int[] icons){
            this.context=context;
        this.datas=datas;
        this.icons=icons;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v= LayoutInflater.from(context).inflate(R.layout.bottom_recycle_layout,null);
        MyViewHolder holder=new MyViewHolder(v);

        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.icon.setImageResource(icons[position]);
        holder.title.setText(datas[position]);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mListener!=null){
                    mListener.OnClick(position);
                }
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(mListener!=null){
                    mListener.OnLongClick(position);
                }
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return datas.length;
    }

    class  MyViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.icon)
        public ImageView icon;
        @BindView(R.id.title)
        public TextView title;
        public  MyViewHolder(View v){
            super(v);
            ButterKnife.bind(this,v);
        }
    }

    //recyclerView 没有点击监听,所以要自己定义
    public interface  OnItemClickListener{
        void OnClick(int position);
        void OnLongClick(int position);
    }

    public  void setOnItemClickListener(OnItemClickListener listener){
        this.mListener=listener;
    }

}

使用:

  View bottom= LayoutInflater.from(context).inflate(R.layout.bottom_sheet_layout,null);
                    RecyclerView recyclerView= (RecyclerView) bottom.findViewById(R.id.recycle);
                    String[] datas=new String[]{"相机","从图片中选取","取消"};
                    int[] icons=new int[]{R.mipmap.camera,R.mipmap.picture,R.mipmap.cancle};
                    BottomSheetAdapter adapter=new BottomSheetAdapter(context,datas,icons);
                    adapter.setOnItemClickListener(new BottomSheetAdapter.OnItemClickListener() {
                        @Override
                        public void OnClick(int position) {
                            switch (position){
                                case 0:
                                    dialog.hide();
                                    ((NoteAddActivity)context).openCamera();
                                    break;
                                case 1:
                                    dialog.hide();
                                    ((NoteAddActivity)context).openGallery();
                                    break;
                                case 2:
                                    dialog.hide();
                                    break;
                                default:
                                    break;
                            }
                        }
                        @Override
                        public void OnLongClick(int position) {
                            Snackbar.make(finalConvertView,"onlongclcik="+position,Snackbar.LENGTH_SHORT).show();
                        }
                    });
                    recyclerView.setAdapter(adapter);
                    recyclerView.addItemDecoration(new DividerItemDecoration(context,LinearLayoutManager.VERTICAL));
                    recyclerView.setLayoutManager(new LinearLayoutManager(context));
                    dialog.setContentView(bottom);
                    dialog.show();

分割线需要自己定义,抄两个过来:

listview的分割

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    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);
            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);
        }
    }

}

gridview的分割

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());
        }
    }
}

具体参考:http://blog.csdn.net/lmj623565791/article/details/45059587

时间: 2024-11-04 11:26:24

Android控件大全(三)——RecyclerView的相关文章

Android控件大全(四)——CoordinatorLayout

CoordinatorLayout 其实就是个高级的FrameLayout,用于协调子布局要使用该控件,需要再gradle中加入: compile 'com.android.support:design:24.2.1' 1.CoordinatorLayout与AppBarLayout 1 <android.support.design.widget.CoordinatorLayout 2 android:layout_height="match_parent" 3 android

Android控件大全(二)——Toolbar

1.隐藏Actionbar 代码中设置:requestWindowFeature(Window.FEATURE_NO_TITLE)     //如果Activity是继承自AppCompatActivity的话,这代码会失效.... 样式中修改: <style name="AppTheme.Base" parent="Theme.AppCompat"> <item name="windowNoTitle">true<

[Android控件]Dialogue大全

在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择.这些功能我们叫它Android Dialog对话框,在我们使用Android的过程中,我归纳了一下,Android Dialog的类型无非也就7种,下面我分别向大家介绍这7种Android Dialog对话框的使用方法,希望对大家能有所帮助. 1.该效果是当按返回按钮时弹出一个提示,来确保无误操作,采用常见的对话框样式. 创建dialog对话框方法代码如下: protected void di

xamarin android——数据绑定到控件(三)

如果当前活动中,只存在一个listview视图,可以借助ListActivity快速的实现一个列表,即当前Activity继承ListActivity.在OnCreate方法中简单的两行代码,就可以创建一个用户列表. string[] items = new string[]{ "列表 1","列表 2","列表 3","列表 4","列表 5","列表 6","列表 7&qu

Android 控件的触摸事件传递与处理

了解Android控件的触摸事件传递与处理对我们日常开发中自定义控件和触摸事件冲突解决有重大意义.Android控件的触摸事件传递和处理主要有以下几个方法,下面一一介绍. 一.与触摸事件有关的几个方法 boolean dispatchTouchEvent(MotionEvent ev);                                                                                               接收到触摸事件时,是否

Android 控件:使用下拉列表框--Spinner

---恢复内容开始--- 一.前段代码 <Spinner android:id="@+id/spin" android:paddingTop="10px" android:layout_width="fill_parent" android:layout_height="50sp"/> <Button android:id="@+id/addList" android:layout_wid

android控件开发之Spinner控件

android控件开发之Spinner控件 概述:android中,Spinner控件主要是用来显示下拉列表,同时,用户可以选择列表中的数据,作为当前的选择 java代码: 此代码中使用了两种方法给Spinner提供数据(method 1和method 2).运行时任选其一即可 方法一: 使用的动态list的形式给Spinner提供数据 方法二: 使用的Strings.xml中定义的固定String array提供数据 根据项目需要,选择相关方法即可 package com.example.sp

Android控件架构与自定义控件详解(二)——自定义View

在自定义View时,我们通常会去重写onDraw()方法来绘制View的显示内容.如果该View还需要使用wrap_content属性,那么还必须重写onMeasure()方法.另外,通过自定义attrs属性,还可以设置新的属性配置值. 在View中通常有一些比较重要的回调方法. onFinishInflate():从XML加载组件后回调. onSizeChanged(;:组件大小改变时. onMeasure():回调该方法来进行测量. onLayout():回调该方法来确定显示的位置. onT

android控件布局 ToggleButton按钮 图片和文字

ToggleButton控件具有checked属性对于要切换状态的功能按钮来说十分好用 这里以phone的开启DTMFTwelveKeyDialer的按钮为例 展示其效果和布局 activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" andro