Andriod开发 SimpleAdapter BaseAdapter

news2024/9/23 23:23:32

1.SimpleAdapter

上一篇博客介绍的ArrayAdapter只能接受数组作为数据源,一般用于显示一行文字,更复杂的内容的显示可以用SimpleAdapter来实现。

SimpleAdapter接受List<Map<String, Object>>作为数据源,每个Map对应一个item(比如购物车里的一件商品,书架上的一本书),Map中的key需要与视图控件相对应,这样value就可以显示到视图控件中了。

2.SimpleAdapter实现

1)item的layout文件

一个item中显示一张图片和一段text

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="70dp"
        tools:src = "@drawable/earth"
        ></ImageView>
    <TextView
        android:id="@+id/tv_name"
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="3"
        android:textColor="@color/teal_200"
        android:textSize="30dp"
        android:text="earth"
        android:gravity="center"
        ></TextView>

</LinearLayout>

2)主界面layout文件

用Spinner作为View容纳item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SpinnerActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Spinner using simple adapter"
        android:textSize="30dp" />

    <Spinner
        android:id="@+id/sp_drop"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:spinnerMode="dropdown"></Spinner>



</LinearLayout>

3)java文件

 对比 ArrayAdapter,SimpleAdapter增加了后两个参数,表明Map<String, Object>中key和item的layout文件中的视图id的对应关系。
 SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.item_icon,
                new String[]{"icon", "name"},
                new int[]{R.id.iv_icon,R.id.tv_name}
                );

其中数据源list的构造如下: 放入每个item的各个属性

List<Map<String, Object>> list = new ArrayList<>();
        for(int i=0;i<stars.length;i++){
            Map<String , Object> mp = new HashMap<>();
            mp.put("icon", icons[i]);
            mp.put("name", stars[i]);
            list.add(mp);
        }

package com.example.chapter08;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleAdapterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {


    public static final String[] stars = {"Venus",  "Earth", "Jupiter", "Mars", "Mercury"};
    public static final int[] icons = {R.drawable.venus,R.drawable.earth,R.drawable.jupiter, R.drawable.mars,R.drawable.mercury};
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_adapter);

        List<Map<String, Object>> list = new ArrayList<>();
        for(int i=0;i<stars.length;i++){
            Map<String , Object> mp = new HashMap<>();
            mp.put("icon", icons[i]);
            mp.put("name", stars[i]);
            list.add(mp);
        }
        SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.item_icon,
                new String[]{"icon", "name"},
                new int[]{R.id.iv_icon,R.id.tv_name}
                );

        Spinner spinner = findViewById(R.id.sp_drop);
        spinner.setAdapter(adapter);
        spinner.setSelection(0);
        spinner.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(this,"You choose " + stars[i], Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}

4)效果图

 3.BaseAdapter 

前文提到SimpleAdapter相比ArrayAdapter可以显示更复杂的数据,那么BaseAdapter 的适应性和灵活性则是三者中最好的,可以接受任何类型的数据源,例如数组、集合或自定义数据类型。

BaseAdapter是一个抽象类,使用时需创建新类继承它,并实现四个方法:getCount()、getItem()、getItemId()和getView()。

其中getView()方法用于将数据项绑定到视图上,可以使用自定义的布局文件来显示数据,也可以在代码中动态创建视图。

BaseAdapter适用于更为复杂的数据绑定场景。

4.BaseAdapter 实现

1)创建实体类,作为BaseAdapter中要操作的对象

package com.example.chapter08.entity;

import com.example.chapter08.R;

import java.util.ArrayList;
import java.util.List;

public class Planet {

    public int image;
    public String name;
    public String desc;

    public Planet(int image, String name, String desc) {
        this.image = image;
        this.name = name;
        this.desc = desc;
    }

    public static final String[] stars = {"Venus",  "Earth", "Jupiter", "Mars", "Mercury"};
    public static final int[] icons = {R.drawable.venus,R.drawable.earth,R.drawable.jupiter, R.drawable.mars,R.drawable.mercury};
    public static final String[] descs = { "Venus is the second planet from the sun and is known as the \"Morning Star\" or \"Evening Star\" due to its bright appearance in the sky.",
            "Earth is the third planet from the sun and the only known planet to support life.",
            "Jupiter is the largest planet in our solar system and is known for its many moons, colorful bands of clouds, and the Great Red Spot, a massive storm that has been raging for over 300 years.",
            "Mars is the fourth planet from the sun and is known as the \"Red Planet\" due to its reddish appearance in the night sky.",
            "Mercury is the smallest planet in our solar system and is closest to the sun, with temperatures that can reach up to 800 degrees Fahrenheit on its surface."
    };

    public static List<Planet> getDefaultList(){
        List<Planet> planets = new ArrayList<>();
        for(int i=0;i<stars.length;i++){
            planets.add(new Planet(icons[i],stars[i], descs[i] ));
        }
        return planets;
    }



}

2)创建新类继承BaseAdapter,并实现四个方法

gteView方法中将Item布局与数据绑定

package com.example.chapter08;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.chapter08.entity.Planet;

import java.util.List;

public class PlanetBaseAdapter extends BaseAdapter {

    public Context myContext;
    public List<Planet> planetList;

    public PlanetBaseAdapter(Context myContext, List<Planet> planetList) {
        this.myContext = myContext;
        this.planetList = planetList;
    }

    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Object getItem(int i) {
        return planetList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = LayoutInflater.from(myContext).inflate(R.layout.item_planet,null);
        ImageView iv = v.findViewById(R.id.iv_icon);
        TextView tv_name = v.findViewById(R.id.tv_name);
        TextView tv_desc = v.findViewById(R.id.tv_desc);


        Planet planet = planetList.get(i);
        iv.setImageResource(planet.image);
        tv_name.setText(planet.name);
        tv_desc.setText(planet.desc);

        return v;
    }
}

3)Activity中Spinner使用BaseAdapter

package com.example.chapter08;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.chapter08.entity.Planet;

import java.util.List;

public class BaseAdapterActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private List<Planet> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_adapter);

        Spinner sp = findViewById(R.id.sp_drop);

        list = Planet.getDefaultList();
        PlanetBaseAdapter baseAdapter = new PlanetBaseAdapter(this, list);

        sp.setAdapter(baseAdapter);
        sp.setSelection(0);
        sp.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(this,"You select " + list.get(i).name, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}

4)效果图

 4.BaseAdapter优化getView()

页面能显示的Item有限,若要显示100个Item,则需要滚动页面。

如果每次都创建新的Item,会浪费内存,所有可以重复使用已经滚出页面的Item。

 代码:

getView()每次判断convertView是否为空,若为空,则新建一个View并把item会用到的控件打包放进View中,若不为空,则代表可以复用已经滚出页面的item的View。

package com.example.chapter08;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.chapter08.entity.Planet;

import java.util.List;

public class PlanetBaseAdapter extends BaseAdapter {

    public Context myContext;
    public List<Planet> planetList;

    public PlanetBaseAdapter(Context myContext, List<Planet> planetList) {
        this.myContext = myContext;
        this.planetList = planetList;
    }

    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Object getItem(int i) {
        return planetList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if(convertView==null){
            convertView = LayoutInflater.from(myContext).inflate(R.layout.item_planet,null);
            holder = new ViewHolder();
            holder.iv = convertView.findViewById(R.id.iv_icon);
            holder.tv_name = convertView.findViewById(R.id.tv_name);
            holder.tv_desc = convertView.findViewById(R.id.tv_desc);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        Planet planet = planetList.get(i);
        holder.iv.setImageResource(planet.image);
        holder.tv_name.setText(planet.name);
        holder.tv_desc.setText(planet.desc);

        return convertView;
    }

    public class ViewHolder{
        ImageView iv;
        TextView tv_name;
        TextView tv_desc;


    }
}

View的setTag()方法用于给View设置一个标记,这个标记可以是任何类型的对象,通常用于在View中存储一些额外的信息,例如View的ID、位置、状态等等。通过setTag()方法设置标记后,可以使用getTag()方法来获取这个标记,并进行相应的操作。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/611328.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

为什么Pitch+Deck是创业者必备技能

投资术语简介&#xff1a;Pitch vs Deck vs BP BP以PPT形式出现的阅读式商业计划书&#xff0c;旨在无人讲解的前提下&#xff0c;通过文字和图表阐述项目商业信息。Deck单纯为营销演讲或融资推介所准备&#xff0c;以极少量文字图标和图像的介绍来辅助演讲的幻灯片。Pitch创业…

Spring Security 6.x 系列【52】扩展篇之集成第三方登录组件JustAuth

有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.1.0 本系列Spring Security 版本 6.1.0 源码地址:https://gitee.com/pearl-organization/study-spring-security-demo 文章目录 1. 简介2. 入门案例3. 流程分析3.1 申请授权3.2 登录4. Spring Security 整…

MySQL 避「坑」指南 —— 你能设置出正确的主键吗?

前言 主键&#xff0c;可以唯一标识表中的某一行&#xff08;记录&#xff09;。合理地设置主键&#xff0c;可以帮助我们准确、快速地找到所需要的数据记录。但是设置出正确的主键似乎并没有那么简单&#xff0c;请思考如下几个问题&#xff1a; 表中的业务字段可以用来做主…

Java-Servlet解析

文章目录 前言Servlet定义内部解析总结servlet接口实际应用的servletGenericServlet类和HttpServlet类 HttpServlet中的设计模式首先看一下模板方法的定义逐步解析 SpringMVC应用 前言 从事Javaweb项目开发有一段时间了&#xff0c;一直不理解它是怎么一回事&#xff0c;后来查…

Fiddler抓包工具之高级工具栏中的Inspectors的使用

高级工具栏中的Inspectors的使用 Inspectors 页签允许你用多种不同格式查看每个请求和响应的内容。JPG 格式使用 ImageView 就可以看到图片&#xff0c;HTML/JS/CSS 使用 TextView 可以看到响应的内容。Raw标签可以查看原始的符合http标准的请求和响应头。Cookies标签可以看到…

【Web服务应用】搭建LNMP架构

搭建LNMP架构 一、编译安装MySQL服务二、安装Nginx服务三、安装配置PHP解析环境四、部署Discuz社区论坛Web应用五、部署博客论坛应用六fpm进程优化 一、编译安装MySQL服务 1.安装MySQL环境依赖包 yum -y install gcc gcc-c ncurses ncurses-devel bison cmake2、创建运行用户 u…

NIMA: Neural Image Assessment

摘要:基于自动学习的图像质量评估技术在评价图像采集管道、存储技术和共享媒体等方面具有广泛的应用价值&#xff0c;近年来已成为图像质量评估研究的热点。尽管这一问题具有主观性&#xff0c;但现有的大多数方法仅对AVA[1]和TID2013[2]等数据集提供的平均意见得分进行预测。我…

电脑怎么录屏?推荐2个好用的win7录屏方法!

案例&#xff1a;win7电脑怎么录屏&#xff1f; 【我的电脑是win7系统&#xff0c;我想录制它的电脑屏幕。有没有小伙伴知道win7电脑怎么录屏&#xff1f;有没有适合win7电脑的录屏工具】 随着数字时代的发展&#xff0c;屏幕录制已经成为一种常见的需求。在教育、演示、游戏…

❤️爆肝熬夜开发了一个基于SSM的办公用品领用系统,现在开源给你!毕设面试学习都不愁了!❤️

大家好&#xff0c;我是兔哥&#xff0c;我又来分享项目啦。 1.写在前面 之前有个粉丝找到我&#xff0c;问有没有什么真正手把手的教SSM框架的视频&#xff0c;说网上找到的大都很复杂或者资料不全。 我说不需要整这么麻烦&#xff0c;我自己给你录一套手把手的教程吧。 ❤…

11.发请求

微信小程序可以请求 HTTPS 类型的接口&#xff08;HTTP不行&#xff09;&#xff0c;请求之前必须将 接口的域名 添加到 信任列表 中 小程序中没有跨域问题&#xff0c;且使用JS原生XML对象发Ajax请求是无效的 目录 1 查看信任的域名 2 添加信任的域名 3 发起GET请求 …

为什么“零信任“对于数据备份和灾难恢复至关重要

零信任模型作为一种突破性的数据备份和安全方法已经崭露头角。近年来&#xff0c;随着网络攻击的蔓延&#xff0c;传统的安全措施已不再足够。据预测&#xff0c;仅在2023年&#xff0c;全球企业因网络犯罪将损失超过8万亿美元。这一惊人的数字凸显了企业迫切需要采取更全面的数…

【方法】如何以“副本方式”打开PPT文件?

在工作中&#xff0c;我们经常需要对PPT文件进行多次修改后才能确定最终版本。 在修改时&#xff0c;如果不想修改原始的PPT文件&#xff0c;我们可以通过“以副本方式”打开PPT&#xff0c;这样PPT就会在原文档所在的文件夹里自动新建一份完全相同的PPT。 创建后对副本的编辑…

Prototypical networks for few-shot learning.

这篇论文是介绍《Prototypical Networks for Few-shot Learning》。作者公布了他的Pytorh代码。如果看不太懂原作者的代码话可以看一下这一个&#xff1a;https://github.com/orobix/Prototypical-Networks-for-Few-shot-Learning-PyTorch 0. Few-shot learning Few-shot lear…

一文通吃:从 ZooKeeper 一致性,Leader选举讲到 ZAB 协议与 PAXOS 算法(下)

本文首发自\[慕课网] &#xff0c;想了解更多IT干货内容&#xff0c;程序员圈内热闻&#xff0c;欢迎关注"慕课网"及“慕课网公众号”&#xff01; 作者&#xff1a;大能 | 慕课网讲师 上篇文章&#xff0c;我们介绍了ZooKeeper集群保证数据一致性和Zookeeper集群Le…

带你全面了解 OAuth2.0

最开始接触 OAuth2.0 的时候&#xff0c;经常将它和 SSO单点登录搞混。后来因为工作需要&#xff0c;在项目中实现了一套SSO&#xff0c;通过对SSO的逐渐了解&#xff0c;也把它和OAuth2.0区分开了。所以当时自己也整理了一篇文章《SSO单点登录原理及实现方式》 最近需要经常和…

STM32单片机GPS北斗无线防丢定位超出距离报警系统NRF24L01

实践制作DIY- GC0136-GPS北斗无线防丢定位超出距离报警系统 基于STM32单片机设计-GPS北斗无线防丢定位超出距离报警系统 二、功能介绍&#xff1a; 主机&#xff1a;STM32F103CxT6系列最小系统板OLED显示器NRF24L01无线通讯模块GPS北斗双模定位模块蜂鸣器距离加减2个按键1个模…

爬虫的操作

目录 爬虫基本 re/etree/beautifulsoup保存本地/连接数据库 基本 re lxml/etree beautifulsoup 保存到本地 传入数据库 大致分为 爬虫基本 re/etree/beautifulsoup保存本地/连接数据库 基本 爬一个很简单的百度新闻热搜 爬排名 热搜名 和热搜指数 百度热搜 我们直…

Lucid VS 特斯拉电驱系统

Lucid如何用更小的电机赶超特斯拉 Lucid 称其电机设计是小型化的&#xff0c;并且一直自夸其Air电动汽车中轻型且“紧凑“的电机轻便到可以放进登机行李箱中。然而&#xff0c;小型只是一个方面。Lucid的电机每个重只有67磅&#xff0c;能够产生670马力的动力&#xff0c;你没…

JAVA 生成微信小程序码-分享码

JAVA生成小程序码(太阳码) 工具类是获取token使用; appId 小程序appID appSecret 小程序秘钥 小程序中得配置分享项&#xff0c;不然图片是裂开的。 开发>开发管理>开发设置 nginx 配置 location ~ ^/share { #、share 你的访问路径default_type text/html;alias /d…

Dart 3.0 语法新特性 | 模式匹配 Patterns

theme: cyanosis 一、 Patterns 是什么 下面是官方对 Patterns 特性的说明 patterns :\ 从下面的第一句中可以知道&#xff0c;Patterns 是一种语法级的特性&#xff0c;而语法特性是一种语言的根基。 Patterns are a syntactic category in the Dart language, like statement…