十分之一代码写完安卓listview adapter 和xml

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

十分之一代码写完安卓listview adapter 和xml

前言:

​ 众所周知,安卓自定义一个自己想要的类的特定布局的listview的流程很复杂

  1. 首先需要在主xml里定义一个listview,
  2. 新建xml画出单个list item的布局,
  3. 新建一个物品类
  4. 新建一个物品的adapter类,布置各种属性,
  5. 在代码里初始化adapter,

这些步骤加起来代码估计已经上百行了,但其实只需要十分之一代码就能解决这个问题,只需要两步

  1. 物品类
  2. 代码添加

传统示例:

主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 <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值