Android快速入门之滚动控件RecyclerView

之前已经用过了ListView控件,虽然可以实现许多放入功能,但是其扩展性还是有一定缺陷的,比如所无法实现横向布局,为此,Android中提供了一个更强大的滚动控件——RecyclerView,它可以实现ListView的功能,同时还在ListView的基础上进行了优化。

RecyclerView基本使用

想要使用RecyclerView,首先我们应该在app的build.gradle中添加相关依赖:

dependencies {
  、、、
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
  、、、
}

之后就可以直接使用RecyclerView控件了:

<!--由于RecyclerView并不是内置在SDK中,所以必须把完整的包路径写下来-->
<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

使用RecyclerView实现ListView相同的效果:

创建主活动CardRecyclerViewActivity,设置布局:

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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

编写子列表的布局:

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

    <ImageView
        android:id="@+id/card_image"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:scaleType="fitCenter"
        android:src="@mipmap/ic_launcher" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="6"
        android:layout_marginTop="3dp"
        android:layout_marginLeft="5dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="Name"
            android:id="@+id/card_name"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="Msg"
            android:id="@+id/card_msg" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="Info"
            android:id="@+id/card_info"/>
    </LinearLayout>

</LinearLayout>

子列表样式:
Android快速入门之滚动控件RecyclerView

创建一个Card类对应我们的列表项,用来封装数据:

public class Card {

    private String name;
    private int imageId;
    private String msg;
    private String info;

    public Card(String name, int imageId,String msg,String info) {
        this.name = name;
        this.imageId = imageId;
        this.msg=msg;
        this.info=info;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }

    public String getMsg() {
        return msg;
    }

    public String getInfo() {
        return info;
    }
}

使用RecyclerView实现一个适配器,新建CardAdapter类,让这个类继承RecyclerView.Adapter,并将泛型置定位CardAdapter.ViewHolder。其中ViewHolder我们定义为内部类。

继承RecyclerView.Adapter需要实现的三个方法:

  • onCreateViewHolder(ViewGroup parent, int viewType):创建ViewHolder实例,在这个方法中可以将列表布局加载进来,之后创建一个ViewHolder实例,并把加载出来的布局传入到构造函数中,最后将ViewHolder实例返回。
  • onBindViewHolder(ViewHolder holder, int position):用于对RecyclerView子项进行赋值,会在每个子项被滚动到屏幕内时执行,我们可以通过position获取当前列表项对应的实例,然偶进行操作。
  • getItemCount():表示RecyclerView中有多少个子项,返回数据源的长度
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder>{

    private Context context;
    private List<Card> mCardList;

    public CardAdapter(Context context,List<Card> cardList) {
        this.context=context;
        mCardList = cardList;
    }

    @Override
    public CardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);

        final ViewHolder holder = new ViewHolder(view);

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Card card = mCardList.get(position);
                Toast.makeText(v.getContext(),   card.getName()+": 奥里给", Toast.LENGTH_SHORT).show();

            }
        });
        holder.cardImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                final Card card = mCardList.get(position);
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                    builder.setIcon(card.getImageId());
                    builder.setTitle(card.getName());
                    builder.setMessage("要拉我上船吗?");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(context,card.getName()+"加入了海贼船", Toast.LENGTH_SHORT).show();
                            }
                        });
                    builder.setNegativeButton("取消", null);
                    builder.create();

                    builder.show();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Card card = mCardList.get(position);
        holder.cardImage.setImageResource(card.getImageId());
        holder.cardName.setText(card.getName());
        holder.cardMsg.setText(card.getMsg());
        holder.cardInfo.setText(card.getInfo());

    }

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

	static class ViewHolder extends RecyclerView.ViewHolder {
        
        View cardView;
        ImageView cardImage;
        TextView cardName;
        TextView cardMsg;
        TextView cardInfo;

        public ViewHolder(View view) {
            super(view);
            cardView = view;
            cardImage = (ImageView) view.findViewById(R.id.card_image);
            cardName = (TextView) view.findViewById(R.id.card_name);
            cardMsg=(TextView) view.findViewById(R.id.card_msg);
            cardInfo=(TextView) view.findViewById(R.id.card_info);
        }
    }
}

适配器准备好就可以编写主界面了:

public class CardRecyclerViewActivity extends AppCompatActivity {

    private List<Card> cardList = new ArrayList<Card>();

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

        initCards();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view_card);
        
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        
//        StaggeredGridLayoutManager layoutManager = new
//        StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(layoutManager);

        //添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.HORIZONTAL));
       
        CardAdapter adapter = new CardAdapter(CardRecyclerViewActivity.this,cardList);
        //设置adapter
        recyclerView.setAdapter(adapter);
    }

    private void initCards() {
        List<Card> list = new ArrayList<Card>();
        list.add(new Card("路飞", R.mipmap.lufei,"【船长】蒙奇·D·路飞(蒙奇·D·路飞 )","1500000000¥"));
        list.add(new Card("索隆", R.mipmap.suolong,"【剑士】罗罗诺亚·索隆","320000000¥"));
        list.add(new Card("乌索普", R.mipmap.wusuopu,"【狙击手】乌索普","200000000¥"));
        list.add(new Card("娜美", R.mipmap.namei,"【航海士】娜美","66000000¥"));
        list.add(new Card("山治", R.mipmap.shanzhi,"【厨师】香吉士","330000000¥"));
        list.add(new Card("乔巴", R.mipmap.qiaoba,"【船医】托尼托尼·乔巴","100¥"));
        list.add(new Card("罗宾", R.mipmap.luobin,"【考古学家】妮可·罗宾 ","130000000¥"));
        list.add(new Card("弗兰奇", R.mipmap.fulanqi,"【船匠】弗兰奇","94000000¥"));
        list.add(new Card("布鲁克", R.mipmap.buluke,"【音乐家】布鲁克","83000000¥"));
        list.add(new Card("香克斯", R.mipmap.xiangkesi,"【四皇】香克斯","4000000000¥"));

        for(int i=0;i<60;i++){
            cardList.add(list.get((int)(Math.random()*10)));
        }
    }

}

运行结果:
Android快速入门之滚动控件RecyclerView

实现不同样式的布局

修改子列表项的布局:card_item.xml

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

    <RelativeLayout
        android:layout_width="150dp"
        android:layout_height="150dp">
        <ImageView
            android:id="@+id/card_image"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:scaleType="fitCenter"
            android:src="@mipmap/ic_launcher" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="Name"
            android:id="@+id/card_name"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Info"
            android:id="@+id/card_info"/>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        android:layout_marginLeft="5dp"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:textSize="15dp"
            android:text="Msg"
            android:id="@+id/card_msg" />

    </LinearLayout>

</LinearLayout>

修改主活动的代码:

//LinearLayoutManager layoutManager=new LinearLayoutManager(this);
//recyclerView.setLayoutManager(layoutManager);

//横向的效果
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);

//网格布局
GridLayoutManager gridLayoutManager = new GridLayoutManager( this,3);
recyclerView.setLayoutManager(gridLayoutManager);


//流式布局
StaggeredGridLayoutManager layoutManager = new
StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);

横向布局:
Android快速入门之滚动控件RecyclerView
网格布局:
Android快速入门之滚动控件RecyclerView

流式布局:
Android快速入门之滚动控件RecyclerView

上一篇:各种通讯的数据传输接口函数的写法(updating...)


下一篇:(Updating)【区间操作数据结构例题】