简单介绍
RecylerView能够灵活地实现大数据集的展示,视图的复用管理比ListView更好,能够显示列表,网格,瀑布流等形式,且不同的ViewHolder能够实现item多元化的功能.
使用准备,添加依赖
implementation 'androidx.recyclerview:recyclerview:1.1.0'
下列例子所有依赖
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
}
RecyclerView 的简单使用
一:RecyclerView 的初始化
recyclerView = findViewById(R.id.recycler1);
recyclerView.setLayoutManager(new LinearLayoutManager(LinearRecycleActivity.this));
//recyclerView.setAdapter(new CLinearAdapter(LinearRecycleActivity.this));简单使用
recyclerView.setAdapter(new CLinearAdapter(LinearRecycleActivity.this, new CLinearAdapter.onItemClickListener() {
@Override
public void click(int pos) {
Toast.makeText(LinearRecycleActivity.this,"InActivity cilik is "+pos,Toast.LENGTH_SHORT).show();
}
}));//这里嵌入了一个lambda表达式,用于实现监听功能
//xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity"
android:padding="50dp">
<Button
android:id="@+id/btn_toListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="toListView"
android:textAllCaps="false"/>
</LinearLayout>
public class CLinearAdapter extends RecyclerView.Adapter <CLinearAdapter.LinearViewHolder>{
private Context context;
private onItemClickListener listener;
CLinearAdapter(Context context,onItemClickListener listener){
this.context = context;
this.listener = listener;
}
@Override
public CLinearAdapter.LinearViewHolder onCreateViewHolder(