ListView控件的使用

目录

一、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:




   

list_item:




    

        

        

        
    

 效果图:

ListView控件的使用_第1张图片

2、SimpleAdapter

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

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

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

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>listtem= new ArrayList<>();

        for (int i = 0; i < imageid.length; i++) {
            Mapmap =new HashMap<>();
            map.put("image",imageid[i]);
            map.put("name",title[i]);
            listtem.add(map);
        }
//        SimpleAdapter(Context context, List> 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 map = (Map) adapterView.getItemAtPosition(i);
                Toast.makeText(MainActivity.this,map.get("name").toString(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

activity_main: 




    

        
    

    

 item:





    

        

        


    

    

        

        
    



效果图:

ListView控件的使用_第2张图片

 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 object);

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

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

 ArrayAdapter例子:

案例一:

        使用的构造器是public ArrayAdapter(Context context, int resource, int textViewResourceId,List 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 adapter = new ArrayAdapter(
                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 adapter = new ArrayAdapter(
                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布局:




    

item布局: 



    
    
    

运行结果:

ListView控件的使用_第3张图片

 案例二:

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 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 {
private int resourceId;
    public MyAdapter(Context context, int textViewResourceId,
                      List 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:




    

fruit_item:



    
    

效果图:

ListView控件的使用_第4张图片

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

你可能感兴趣的:(UI,android)