下图是淘宝上瀑布流的一个应用场景,今天我们就来用Recycler View实现以下瀑布流效果
一:创建Activity
activity中 核心代码为
(new StaggeredGridLayoutManager(2,));
该行代码使用layoutmanager实现一个两列的垂直布局,API解释如下
new StaggeredGridLayoutManager(行数/列数,水平/垂直)
-
package .;
-
-
import ..AppCompatActivity;
-
import .Bundle;
-
import ..RecyclerView;
-
import ..StaggeredGridLayoutManager;
-
-
import .demo4.R;
-
-
public class PuRecyclerViewActivity extends AppCompatActivity {
-
private RecyclerView mRvPu;
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_pu_recycler_view);
-
mRvPu=(RecyclerView)findViewById(R.id.rv_pu);
-
//设置布局方式,2列,垂直
-
(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
-
(new StaggeredGridAdapter(PuRecyclerViewActivity.this));
-
}
-
}
二:Adapter的构建
没什么特别的地方
-
package .;
-
-
import ;
-
import .;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
-
import .;
-
-
import ;
-
import ;
-
-
public class StaggeredGridAdapter extends RecyclerView.Adapter<>{
-
-
private Context mContext;
-
private mListener;
-
private List<String> list=new ArrayList<>();
-
-
public StaggeredGridAdapter(Context mContext) {
-
this.mContext = mContext;
-
for(int i=0;i<30;i++){
-
(("%s-%s", i/10+1,i));
-
}
-
}
-
-
@Override
-
public onCreateViewHolder(ViewGroup parent, int viewType) {
-
return new LinearViewHolder((mContext).inflate(.layout_staggere_grid_item,parent,false));
-
}
-
-
@Override
-
public void onBindViewHolder( holder, int position) {
-
if(position%2==0){
-
(.baby1);
-
}
-
else{
-
(.baby2);
-
}
-
-
}
-
-
@Override
-
public int getItemCount() {
-
return 30;
-
}
-
-
class LinearViewHolder extends RecyclerView.ViewHolder{
-
private ImageView mImageView;
-
public LinearViewHolder(View itemView){
-
super(itemView);
-
mImageView=(ImageView) ();
-
}
-
}
-
}
三:布局文件 layout_staggere_grid_item.xml
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout
-
xmlns:android="/apk/res/android"
-
android:layout_width="match_parent"
-
android:layout_height="wrap_content"
-
android:orientation="vertical">
-
-
<ImageView
-
android:id="@+id/iv"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:layout_margin="2dp"
-
android:scaleType="centerCrop"/>
-
</LinearLayout>
当运行时候可得到如下效果,自此一个瀑布流就实现了,之后可以根据业务场景写点击事件或是UI上加入TextView做其他用途等,这里有可能会有OOM问题,下次在讲啦