- 这是一个简单的Demo,使用AndroidX,看效果。
- 简单使用步骤:
- project目录下build.gradle,需要加jitpack地址,否则不能识别BaseRecyclerViewAdapterHelper这个库。
allprojects {
repositories {
......
maven { url "https://jitpack.io" }
}
}
- app 目录下的build.gradle:
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'
}
- 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));
adapter = new NameAdapter(R.layout.item_name, getNameList());
rv.setAdapter(adapter);
}
private List<String> getNameList() {
ArrayList<String> nameList = new ArrayList<>();
nameList.add("刘德华");
nameList.add("张学友");
nameList.add("黎明");
nameList.add("郭富城");
nameList.add("任达华");
nameList.add("洪金宝");
nameList.add("周星驰");
nameList.add("成龙");
return nameList;
}
}
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.item_name;
}
@Override
protected void convert(BaseViewHolder helper, String item) {
helper.setText(R.id.tv_name, item);
}
}
SimpleQuickAdapter只是为了简化NameAdapter,经常会忘记传泛型BaseViewHolder。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);
}
}
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>
item_name.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>