- Ceci est une simple démo, utilisez AndroidX pour voir l'effet.
- Étapes simples à utiliser:
- Dans build.gradle dans le répertoire du projet, vous devez ajouter l'adresse jitpack, sinon la bibliothèque BaseRecyclerViewAdapterHelper ne sera pas reconnue.
allprojects {
repositories {
......
maven { url "https://jitpack.io" }
}
}
- build.gradle dans le répertoire de l'application:
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
......
minSdkVersion 16
targetSdkVersion 30
......
}
......
}
dependencies {
......
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.40'
}
- Code MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView rv;
NameAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv = findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
ArrayList<String> nameList = new ArrayList<>();
nameList.add("刘德华");
nameList.add("张学友");
nameList.add("黎明");
nameList.add("郭富城");
nameList.add("任达华");
nameList.add("洪金宝");
nameList.add("周星驰");
nameList.add("成龙");
adapter = new NameAdapter(R.layout.itme_name, nameList);
rv.setAdapter(adapter);
}
}
Code NameAdapter:
public class NameAdapter extends SimpleQuickAdapter<String> {
public NameAdapter(int layoutId, @Nullable List<String> data) {
super(layoutId, data);
}
@Override
public int getItemLayoutId() {
return R.layout.itme_name;
}
@Override
protected void convert(BaseViewHolder helper, String item) {
helper.setText(R.id.tv_name, item);
}
}
SimpleQuickAdapter est juste pour simplifier le NameAdapter et oublie souvent de transmettre le BaseViewHolder générique. Code SimpleQuickAdapter.
public abstract class SimpleQuickAdapter<T> extends BaseQuickAdapter<T, BaseViewHolder> {
/**
* @return 此方法只是便于在Adapter的内部,直接看到布局id
*/
public abstract int getItemLayoutId();
public SimpleQuickAdapter(int layoutId, @Nullable List<T> data) {
super(layoutId, data);
}
}
code activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
code_élément.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:textColor="#333333"
android:textSize="16sp"
tools:text="刘德华">
</TextView>