今天复习了一遍RecyclerView的基本用法,好长时间没有自己写过,加上之前用的也少,发现基本上都快忘了,看来以后还要多练。
首先在Gradle添加依赖
compile 'com.android.support:recyclerview-v7:21.0.+'
创建布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.android.lxx.recyclerviewdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Activity,通过LayoutManager可以设置不同的布局
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<String> mData;
private HomeAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv);
mAdapter=new HomeAdapter(initData());
//创建默认的线性LayoutManager
// recyclerView.setLayoutManager(new LinearLayoutManager(this));
//创建GridView网格布局管理器
// recyclerView.setLayoutManager(new GridLayoutManager(this,5));
//创建瀑布就式布局管理器
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
StaggeredGridLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
}
private ArrayList<String> initData() {
mData = new ArrayList<>();
for (int i = 'A'; i < 'Z'; i++) {
mData.add((char) i + "");
}
return mData;
}
}
item布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/num"
android:gravity="center"
android:layout_width="50dp"
android:layout_height="50dp" />
</LinearLayout>
Adapter
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
ArrayList<String> mData;
public HomeAdapter(ArrayList<String> list) {
this.mData = list;
}
//创建新的view,被LayoutManager调用
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
//将数据与界面进行绑定
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
/**
* 自定义的ViewHolder,持有每个Item布局界面的所有元素
* */
class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tv;
public MyViewHolder(View itemView) {
super(itemView);
tv= (TextView) itemView.findViewById(R.id.num);
}
}
}