目录

一、ListView的属性

二、常用适配器(Adapter)

1、BaseAdapter

BaseAdapter例子:

2、SimpleAdapter

SimpleAdapter例子:

 3、ArrayAdapter

 ArrayAdapter例子:

一、ListView的属性

常用属性:

属性名称功能描述
android:listSelector当条目被点击后,改变条目的背景颜色
android:dividerHeight设置分割线的高度
android:divider设置分割线的颜色
android:scrollbars是否显示滚动条
android:cacheColorHint去除listview拖动时的背景色
android:fadingEdge去掉上边和下边的黑色阴影

二、常用适配器(Adapter)


        在给ListView添加数据的时候会使用到适配器,适配器是数据和视图之间的桥梁。下面就简单介绍一下ListView常用的适配器。

1、BaseAdapter

        BaseAdapter是一个抽象类,它的主要用途是将一组数据传到ListView、Spinner、Callery及GridView等UI显示组件,该类有四个抽象方法,通常在写适配器类时,需要继承BaseAdapter,实现其四个抽象方法。

BaseAdapter中的方法
方法名功能描述
public int getCount()获取Item条目的总数
public Object getItem(int position)根据position获取某个条目对象
public long getItemId(int position)根据位置获取某个条目的id
public View getView(int position,View convertView, ViewGroup parent)获取相应的position对应的item视图,position是当前的item的位置。convertView是用于复用旧图,parent用来加载XML布局

BaseAdapter例子:

MainActivity:

package com.example.baseadapter_listview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView mListView;
    public String titles[] = {"桌子","苹果","蛋糕","毛衣"};
    public String prices[] = {"1800元","10/kg","30元","70元"};
    public int icons[] = {R.drawable.table,R.drawable.apple,R.drawable.cake,R.drawable.sweater};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mListView = findViewById(R.id.list_view);
        MyAdapter adapter = new MyAdapter();
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,"物品:"+titles[position]+"   价格:"+prices[position],Toast.LENGTH_LONG).show();
            }
        });
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Object getItem(int position) {
            return titles[position];
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView==null) {
                convertView = View.inflate(MainActivity.this,R.layout.list_item,null);
                holder = new ViewHolder();
               holder.title = convertView.findViewById(R.id.title_t);

                holder.price = convertView.findViewById(R.id.price);
                holder.imageView = convertView.findViewById(R.id.image_i);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.title.setText(titles[position]);
            holder.imageView.setImageResource(icons[position]);
            holder.price.setText(prices[position]);
            return convertView;
        }
    }
    class ViewHolder{
        TextView title,price;
        ImageView imageView;
    }
}

总体来说,BaseAdapter类的实现步骤如下:
(1)、创建bean数据集合对象,用来封装数据。

(2)、在MainActivity中,初始化数据集合对象bean。

(3)、创建ViewHolder类,创建布局映射关系。

(4)、 判断convertView,为空则创建,并设置Tag,不为空则通过Tag取出ViewHolder。

(5)、为ViewHolder的控件设置数据。

 activity_main:

<?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=".MainActivity">

   <ListView
       android:id="@+id/list_view"
       android:scrollbars="vertical"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

</LinearLayout>

list_item:

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

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/image_i"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:paddingLeft="10dp"
            android:paddingTop="10dp"
            android:src="@drawable/ic_launcher_background" />

        <TextView
            android:paddingTop="15dp"
            android:id="@+id/title_t"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingLeft="180dp"
            android:text="我是标题啊"
            android:textSize="26sp" />

        <TextView
            android:id="@+id/price"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="150dp"
            android:paddingTop="70dp"
            android:text="000" />
    </RelativeLayout>

</LinearLayout>

 效果图:

2、SimpleAdapter

        SimpleAdapter是继承BaseAdapter的,实现了BaseAdapter的四个抽象方法封装,因此,使用SimpleAdapter时,在其构造器传入参数即可。

public SimpleAdapter(Context context, List<?extends Map<String,?>>data, int resource, String [ ] from, int [ ] to) 

参数含义
context表示上下文
data数据集合,data中的每一项对应的ListView控件的条目的数据
resourceItem布局的id 
fromMap集合的key值
toItem布局中的对应控件

SimpleAdapter例子:

MainActivity:

package com.example.simpleadapter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int []imageid =new int[]{R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img6,R.drawable.img4,R.drawable.img5} ;
        String title []= new String[]{"图片一","图片二","图片三","图片四","图片五","图片六"};

        List<Map<String,Object>>listtem= new ArrayList<>();

        for (int i = 0; i < imageid.length; i++) {
            Map<String,Object>map =new HashMap<>();
            map.put("image",imageid[i]);
            map.put("name",title[i]);
            listtem.add(map);
        }
//        SimpleAdapter(Context context, List<? extends Map<String, ?>> data,
//        int resource, String[] from, int[] to)
//        context:上下文
//        data:数据源,一个包含Map的数据集合
//        resource:item的布局文件
//        from:数据来源的key的数组,与data的Map里的key对应
//        to:  from中的每一项数据源 对应到的 item布局中对应组件的 id。
        SimpleAdapter adapter =new SimpleAdapter(this,listtem,R.layout.item,new String[]{"name","image"}
                ,new int []{R.id.title,R.id.photo});
        ListView listView = findViewById(R.id.listview);
        listView.setAdapter(adapter);
        
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String,Object> map = (Map<String, Object>) adapterView.getItemAtPosition(i);
                Toast.makeText(MainActivity.this,map.get("name").toString(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

activity_main: 

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="408dp"
            android:layout_height="?attr/actionBarSize"
            android:background="#ffff00"
            android:layout_gravity="center"
            app:title="摄影比赛"
            app:titleMarginStart="175dp"/>
    </LinearLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

 item:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <ImageView
            android:id="@+id/photo"
            android:layout_width="match_parent"
            android:layout_height="236dp"
            android:scaleType="fitXY"
            android:src="@drawable/img1" />

        <TextView
            android:layout_width="141dp"
            android:layout_height="51dp"
            android:background="@color/white"
            android:gravity="center"
            android:text="距离结束12天"
            android:textColor="@color/black"
            android:textSize="20dp" />


    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/title"
            android:layout_width="240dp"
            android:layout_height="57dp"
            android:gravity="center"
            android:text="秋天的味道"
            android:textSize="30sp" />

        <TextView
            android:layout_width="166dp"
            android:layout_height="35dp"
            android:layout_gravity="center"
            android:text="尼康专业相机"
            android:textSize="20dp"
            android:gravity="center"/>
    </LinearLayout>



</LinearLayout>

效果图:

 3、ArrayAdapter

       ArrayAdapter也是继承BaseAdapter的,实现了BaseAdapter的四个抽象方法封装,因此,使用ArrayAdapterr时,在其构造器传入参数即可。

                                        ArrayAdapter的构造器如下:

public ArrayAdapter(Context context, int resource);

public ArrayAdapter(Context context, int resource, int textViewResourceId);

public ArrayAdapter(Context context, int resource, T [ ] object);

public ArrayAdapter(Context context, int resource, int textViewResourceId, T [ ] object);

public ArrayAdapter(Context context, int resource, List<T> object);

public ArrayAdapter(Context context, int resource, int textViewResourceId,List<T> object);

参数含义
context表示上下文
texViewResourceIdItem布局相应的TextView的id
resourceItem布局的id
T [] objects需要适配的数组类型的数据
List <T> objects需要适配的集合类型的数据

 ArrayAdapter例子:

案例一:

        使用的构造器是public ArrayAdapter(Context context, int resource, int textViewResourceId,List<T> object);

MainActivity布局:

package com.example.arrayadapter_listview;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
    // 准备数据
    private String[] data = { "Apple", "Banana", "Orange", "Watermelon",
            "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
            "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",
            "Pineapple", "Strawberry", "Cherry", "Mango" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MainActivity.this,R.layout.item,R.id.text,data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        // 绑定适配器
        listView.setAdapter(adapter);
package com.example.arrayadapter_listview;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    // 准备数据
    private String[] data = { "Apple", "Banana", "Orange", "Watermelon",
            "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
            "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",
            "Pineapple", "Strawberry", "Cherry", "Mango" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MainActivity.this,R.layout.item,R.id.text,data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        // 绑定适配器
        listView.setAdapter(adapter);
        // 点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,data[position],Toast.LENGTH_LONG).show();
            }
        });
    }
}

    }
}

 activity_main布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>
</LinearLayout>

item布局: 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <TextView
        android:text="111"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:gravity="center"
        android:id="@+id/text"
        />
    </LinearLayout>
</LinearLayout>

运行结果:

 案例二:

MainActivity:

package com.example.arrayadapter2_listview;

import androidx.appcompat.app.AppCompatActivity;

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

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

public class MainActivity extends AppCompatActivity {
    // 准备数据
List<Fruit> mFruits = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化数据
        initData();
        // 创建适配器
        MyAdapter myAdapter = new MyAdapter(MainActivity.this,R.layout.fruit_item,mFruits);
        ListView listView = findViewById(R.id.list_view);
        // 设置适配器
        listView.setAdapter(myAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = mFruits.get(position);
                Toast.makeText(MainActivity.this,"您点击了"+fruit.getName(),Toast.LENGTH_LONG).show();
            }
        });
    }

    private void initData() {
        for (int i = 0; i < 3; i++) {
            Fruit apple = new Fruit("苹果",R.drawable.apple);
            mFruits.add(apple);
            Fruit orange = new Fruit("橘子",R.drawable.orange);
            mFruits.add(orange);
            Fruit strawberry = new Fruit("草莓",R.drawable.strawberry);
            mFruits.add(strawberry);
            Fruit watermelon = new Fruit("西瓜",R.drawable.watermelon);
            mFruits.add(watermelon);
            Fruit lemon = new Fruit("柠檬",R.drawable.lemon);
            mFruits.add(lemon);
            Fruit pear = new Fruit("梨子",R.drawable.pear);
            mFruits.add(pear);
            Fruit kiwi = new Fruit("猕猴桃",R.drawable.kiwi);
            mFruits.add(kiwi);
            Fruit tomato = new Fruit("西红柿",R.drawable.tomato);
            mFruits.add(tomato);
            Fruit grape = new Fruit("葡萄",R.drawable.grape);
            mFruits.add(grape);
        }
    }
}

MyAdapter:

package com.example.arrayadapter2_listview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

public class MyAdapter extends ArrayAdapter<Fruit> {
private int resourceId;
    public MyAdapter(Context context, int textViewResourceId,
                      List<Fruit> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent,
                    false);
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = (ImageView) view.findViewById
                    (R.id.fruit_image);
            viewHolder.fruitName = (TextView) view.findViewById (R.id.fruit_name);
            view.setTag(viewHolder); // 将ViewHolder存储在View中
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
        }
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }
    class ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
    }

}

Fruit:

package com.example.arrayadapter2_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_main:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view"
        android:scrollbars="vertical"
/>
</LinearLayout>

fruit_item:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:scaleType="fitXY"
        android:src="@drawable/apple"
        android:id="@+id/fruit_image"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    <TextView
        android:textSize="25sp"
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="50dp" />
</LinearLayout>

效果图:

传送门ListView的子类ExpandableListView:ExpandableListView控件的使用_敬往事一杯酒哈的博客-CSDN博客

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐