十分之一代码写完安卓listview adapter 和xml
前言:
众所周知,安卓自定义一个自己想要的类的特定布局的listview的流程很复杂
首先需要在主xml里定义一个listview,新建xml画出单个list item的布局,新建一个物品类新建一个物品的adapter类,布置各种属性,在代码里初始化adapter,
这些步骤加起来代码估计已经上百行了,但其实只需要十分之一代码就能解决这个问题,只需要两步
物品类代码添加
传统示例:
主xml
<ListView
android:id="@+id/lv_menu"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
单个布局xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/lv_item_selector"
>
<TextView
android:id="@+id/animalName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"/>
<ImageView
android:id="@+id/animalImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="centerCrop"
/>
</RelativeLayout>
物品类
package com.eric.test1;
public class Animal {
public String name;
public int img;
public Animal(String name, int img) {
this.name = name;
this.img = img;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
adapter类
package com.eric.test1;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import <

本文介绍如何使用更少的代码(约十分之一)来完成安卓ListView的adapter和XML布局设置。传统方法通常涉及复杂的步骤和大量代码,但通过新的Compose方法,可以显著简化这一过程。文中提供了一个简单的Compose示例,并展示了运行结果。

530

被折叠的 条评论
为什么被折叠?



