RecyclerView使用解析(一)——替代ListView
主Acticvity的XML:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_viewh"
android:layout_width="match_parent"
android:layout_height="match_parent" />
item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="10dp" />
</LinearLayout>
Adapter代码与RecyclerView使用解析(一)——替代ListView相同:
数据类:
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
Activity全代码:
private List<Fruit> hList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initR();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_viewh);
StaggeredGridLayoutManager layoutManager1 = new
StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager1);
SecondAdapter adapter1 = new SecondAdapter(hList);
recyclerView.setAdapter(adapter1);
}
private void initR() {
Fruit apple = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(apple);
Fruit banana = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(banana);
Fruit orange = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(orange);
Fruit watermelon = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(watermelon);
Fruit pear = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(pear);
Fruit grape = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(grape);
Fruit pineapple = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(pineapple);
Fruit strawberry = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(strawberry);
Fruit cherry = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(cherry);
Fruit mango = new Fruit(
getRandomLengthName("阿弥陀佛"), R.mipmap.hs);
hList.add(mango);
}
private String getRandomLengthName(String name) {
Random random = new Random();
int length = random.nextInt(20) + 1;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
builder.append(name);
}
return builder.toString();
}
代码下载:https://download.csdn.net/download/nmgsyps2017/20365626?spm=1001.2014.3001.5501