Android RecyclerView 瀑布流

时间:2023-03-08 16:51:20

Android RecyclerView 瀑布流

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"> <ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="fitXY"
android:adjustViewBounds="true"/> </LinearLayout>

item_layout.xml

导入RecyclerView包

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView>
</RelativeLayout>

activity_main.xml

 public class MainActivity extends AppCompatActivity {

     RecyclerView mRecycleView;
List<Image> mList = new ArrayList<>(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mRecycleView = (RecyclerView) findViewById(R.id.recyclerview);
//初始化数据
initData();
//设置适配器
mRecycleView.setAdapter(new MyAdapter());
//设置布局管理器
//mRecycleView.setLayoutManager(new LinearLayoutManager(this));//与ListView类似
mRecycleView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
//设置item分割线 //设置item动画
} private void initData() {
for (int i = 1; i <= 20; i++) {
try { mList.add(new Image(R.mipmap.class.getField("img0"+i).getInt(null))); } catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
} } //布局的内容组件
class MyViewHolder extends RecyclerView.ViewHolder{ ImageView iv; public MyViewHolder(View itemView) {
super(itemView);
iv = (ImageView) itemView.findViewById(R.id.iv);
}
} //适配器,继承RecyclerView.Adapter,泛型,里面必须是Recycler.ViewHolder的子类
class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{ /**
* 一个页面没有加载完毕,会持续调用该方法。
* @param parent
* @param viewType
* @return
*/
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//创建ViewHolder
//导入布局
View layout = View.inflate(getBaseContext(),R.layout.item_layout,null);
MyViewHolder viewHolder = new MyViewHolder(layout);
return viewHolder;
} @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//为每一个布局设置属性。
//holder 组件
//当前第几项, mList.get(position)拿到数据,给holder设置 holder.iv.setImageResource(mList.get(position).imgId);
} @Override
public int getItemCount() {
return mList.size();
}
} class Image{
int imgId;
public Image(int imgId){
this.imgId = imgId;
}
}
}

MainActivity.java