package com.qianqian.liqianqiandemo1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView rlv;
List<String> data=new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到recyclelview
//第一种
rlv= (RecyclerView) findViewById(R.id.rlv);
/* LinearLayoutManager mar=new LinearLayoutManager(this);
mar.setOrientation(LinearLayoutManager.VERTICAL);
rlv.setLayoutManager(mar);*/
//第二种
// GridLayoutManager mar=new GridLayoutManager(this,3);
//第三种
StaggeredGridLayoutManager mar = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
rlv.setLayoutManager(mar);
//创建数据源
for (int i = 0; i <20; i++) {
data.add("条目"+i);
}
//设置适配器
MyAdapter adapter=new MyAdapter();
rlv.setAdapter(adapter);
}
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
//RecyclerView显示的子View
//该方法返回是ViewHolder,当有可复用View时,就不再调用
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= View.inflate(MainActivity.this,R.layout.item,null);
return new ViewHolder(v);
}
//将数据绑定到子View,会自动复用View
@Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
holder.tv.setText(data.get(position));
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,100+(int)(Math.random()*50));
holder.iv.setLayoutParams(lp);
}
//RecyclerView显示数据条数
@Override
public int getItemCount() {
return data.size();
}
//自定义的ViewHolder,减少findViewById调用次数
class ViewHolder extends RecyclerView.ViewHolder{
ImageView iv;
TextView tv;
//在布局中找到所含有的UI组件
public ViewHolder(View itemView) {
super(itemView);
tv=itemView.findViewById(R.id.textView);
iv=itemView.findViewById(R.id.imageView);
}
}
}
}
RecyclerView1
最新推荐文章于 2023-10-04 07:00:00 发布