RecyclerView

compile 'com.android.support:recyclerview-v7:24.2.1'
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</LinearLayout>
class XXXViewHolder extends RecyclerView.ViewHolder{
    public XXXViewHolder(View view){
        super(view);
    }
}
public class XXXAdapter extends RecyclerView.Adapter<XXXViewHolder>{

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

    @Override
    public void onBindViewHolder(XXXViewHolder holder, int position){

    }

    @Override
    public int getItemCount(){
        return ...;
    }
}
RecyclerView recyclerView = findViewById(...);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);

XXXAdapter adapter = new XXXAdapter(...);

recycler.setAdapter(adapter);

横向滚动效果

RecyclerView recyclerView = findViewById(...);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//------------>
recyclerView.setLayoutManager(layoutManager);

XXXAdapter adapter = new XXXAdapter(...);

recycler.setAdapter(adapter);

RecyclerView还提供了GridLayoutManager和StaggeredGridLayoutManager这两种内置的布局排列方法。

GridLayoutManager可以用于实现网格布局。
StaggeredGridLayoutManager可以用于实现瀑布流布局。

RecyclerView recyclerView = findViewById(...);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);

XXXAdapter adapter = new XXXAdapter(...);

recycler.setAdapter(adapter);

RecyclerView的点击事件

不同于ListView的是,RecyclerView并没有提供类似于setOnItemClickListener()这样的注册监听器方法,而是需要我们自己给子项具体的View去注册点击事件。

打赏