AndroidAndroid学习程序猿阵线联盟-汇总各类技术干货

Android 5.0新控件—RecyclerView的基本用法

2016-09-01  本文已影响1264人  程序员K哥

未经本人授权,不得转载!否则必将维权到底

RecyclerView是Google在API 21下support.V7包里的控件,用来替代ListView。
官网对RecyclerView的描述为:A flexible view for providing a limited window into a large data set。
个人翻译(英文水平有限...):RecyclerView是为一个大数据的集合提供一个受限制的窗口的灵活性的View。

一、使用RecyclerView的前提条件

想使用RecyclerView,一定要在build.gradle中引入compile 'com.android.support:recyclerview-v7:24.0.0'依赖。

二、使用RecyclerView的优缺点

优点:

缺点:

三、RecyclerView的具体实现

先来看下效果图:
图例1.png 图例2.png 图例3.png

使用方法如下:

1.在xml布局里面直接添加RecyclerView控件(跟ListView差不多),在布局中我添加了一个Spinner按钮来选择不同的Item展示模式,两个Button按钮用来添加或者删除Item。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.it.keithxiaoy.recycleview.MainActivity">

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

    <Spinner
        android:layout_alignParentBottom="true"
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
    </Spinner>

    <Button
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/spinner"
        android:id="@+id/b1"
        android:text="add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/b1"
        android:id="@+id/b2"
        android:text="delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>
2.Activity界面分析
 mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
 mLinearLayoutManager = new LinearLayoutManager(this);
 mRecyclerView.setLayoutManager(mLinearLayoutManager);
  myRecycleViewAdapter = new MyRecycleViewAdapter(datas);
  mRecyclerView.setAdapter(myRecycleViewAdapter);
        //设置item的点击事件
        myRecycleViewAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final View view, int position) {
                //设置点击动画
                view.animate()
                        .translationZ(15f)
                        .setDuration(300)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                view.animate()
                                        .translationZ(1f)
                                        .setDuration(500)
                                        .start();
                            }
                        }).start();
            }
        });
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                if (position == 0){
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                }else if (position == 1){
                    mRecyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
                }else if (position == 2)
                    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
            }
下面是完整的Activity的代码:
package com.it.keithxiaoy.recycleview;
import ...
/** * Created by KeithXiaoY on 2016/8/31. */
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private RecyclerView mRecyclerView;
    private MyRecycleViewAdapter myRecycleViewAdapter;
    private List<String> datas = new ArrayList<>();
    private LinearLayoutManager mLinearLayoutManager;
    private Spinner mSpinner;
    private static final String[] m={"竖着的RecycleView","GridView类型的RecycleView","瀑布流","还没想好其他效果","其他"};
    private ArrayAdapter<String> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        Button add = (Button) findViewById(R.id.b1);
        Button delete = (Button) findViewById(R.id.b2);
        add.setOnClickListener(this);
        delete.setOnClickListener(this);
        mSpinner = (Spinner) findViewById(R.id.spinner);

        //将可选内容与ArrayAdapter连接起来
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,m);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //将adapter 添加到spinner中
        mSpinner.setAdapter(adapter);
        //设置默认值
        mSpinner.setVisibility(View.VISIBLE);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        // do not change the size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
                if (position == 0){
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                }else if (position == 1){
                    mRecyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
                }else if (position == 2)
                    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        for (int i = 0; i < 3 ; i++) {
            datas.add("KeithXiaoY");
        }
        myRecycleViewAdapter = new MyRecycleViewAdapter(datas);
        mRecyclerView.setAdapter(myRecycleViewAdapter);
        //设置item的点击事件
        myRecycleViewAdapter.setOnItemClickListener(new MyRecycleViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final View view, int position) {
                //设置点击动画
                view.animate()
                        .translationZ(15f)
                        .setDuration(300)
                        .setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                view.animate()
                                        .translationZ(1f)
                                        .setDuration(500)
                                        .start();
                            }
                        }).start();
            }
        });
    }
    public void  add(View view){
        datas.add("KeithXiaoY");
        int position  = datas.size();
        if (position > 0){
            myRecycleViewAdapter.notifyDataSetChanged();
        }
    }
    public void  delete(View view){
        int position  = datas.size();
        if (position >  0){
            datas.remove(position - 1);
            myRecycleViewAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.b1 :
                add(view);
                break;
            case R.id.b2 :
                delete(view);
                break;
        }
    }
}
3.RecycleView的Adapter和ListView的Adapter还是有点区别,来看看RecycleView的Adapter
package com.it.keithxiaoy.recycleview;
import ...
/** * Created by KeithXiaoY on 2016/8/31. */
public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.ViewHolder> {

    private List<String> mData;
    public MyRecycleViewAdapter(List<String> data) {
        mData = data ;
    }
    public OnItemClickListener itemClickListener;
    public  void setOnItemClickListener(OnItemClickListener itemClickListener){
        this.itemClickListener = itemClickListener;
    }
    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }

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

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textView.setText(mData.get(position)+ position);
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public TextView textView ;
        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
            textView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (itemClickListener != null){
                itemClickListener.onItemClick(view,getPosition());
            }
        }
    }

}
4.RecycleView的item布局就是一个TextView,这里代码就不贴了,实际项目中有一些是结合CardView配合使用。

注意事项:

结束语:

本文只是介绍了RecycleView的基本用法,还有很多高级的用法,本人还未领会。不足之处,诸君谅解...


欢迎关注我的微信公众号与我交流,希望与大家共同成长,未来是属于我们的!
上一篇下一篇

猜你喜欢

热点阅读