Android入门之ListView

这篇文章我想来记录一下自己学习android开发中关于ListView布局的介绍以及使用,方便自己以后的翻阅和学习。

1. ListView简介

ListView 算得上是Android中最常用的控件之一了,几乎所有的应用程序都能够见到它的身影。其实简单来说,就是我们Android手机中见到的滚动列表(也有可能通过RecyclerView实现,下一篇文章可能进行介绍),向查看QQ聊天等翻看列表都是在使用这个控件。

2. ListView使用过程

1)在Activity的布局xml中加入ListView;
2)准备数据
3)构建适配器
4)将适配器添加到ListView中

3. Adapter

在Android开发中的Adapter,可以简单地分为ArrayAdapter,BaseAdapter,CursorAdapter,HeaderViewListAdapter,ResourceCursorAdapter,SimpleAdapter,SimpleCursorAdapter,SimpleCursorAdapter,WrapperListAdapter,下面的内容分别以ArrayAdapter、SimpleAdapter和自定义ArrayAdapter进行呈现

4. 添加ListView布局

xxActivity的布局文件activity_xx.xml如下


    
对,很简单,这里我把ListView的ID设置为list_view,将宽度和高度都设置为match_parent,让ListView占满整个布局空间

5. StringListViewActivity

5.1 代码

这是一个简单的ListView的Activity,在这个Activity里面需要准备ListView展示的数据,可以是来自数据库等任何地方,这里的数据我就直接简单构造,然后适配器是ArrayAdapter,并指定它的泛型为String,在其构造器中依次传入当前上下文、ListView子项布局的id,以及要适配的数据。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class StringListViewActivity extends AppCompatActivity {


    private String[] data = {"Apple", "Balana", "Orange", "Watermelon", "pear"
            , "Grape", "Pineapple", "Strawberry", "Cherry", "Mango", "Pineapple", "Strawbery"
            , "Cherry", "Mango"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stringlistview);
        //构造适配器,android.R.layout.simple_list_item_1是Android内置的布局文件,其实就是一个TextView
        ArrayAdapter adapter = new ArrayAdapter(StringListView.this, android.R.layout.simple_list_item_1, data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        //装载适配器
        listView.setAdapter(adapter);
    }
}

5.2 效果

Android入门之ListView_第1张图片


6. SimpleListViewActivity

6.1 代码

这是一个带标题的ListView列表,使用simpleAdapter需要注意的需要使用Map item来保存列表中每一项的显示的title与text,构建Adapter时将map中的数据传入,列表就会被适配器自动构建。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.*;

public class SimpleListViewActivity extends AppCompatActivity {

    private String[] data = {"Apple", "Balana", "Orange", "Watermelon", "pear"
            , "Grape", "Pineapple", "Strawberry", "Cherry", "Mango", "Pineapple", "Strawbery"
            , "Cherry", "Mango"};
    private String[] creation = {"created in China", "create in America", "create in England", "create in Russia"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stringlistview);
        //构造数据
        ArrayList> mData= new ArrayList>();;
            for(int i =0; i < data.length; i++) {
                Map item = new HashMap();
                item.put("fruit", data[i]);
                item.put("creation", creation[i%4]);
                mData.add(item);
            }


        //构造适配器,android.R.layout.simple_list_item_2是Android内置的布局文件,可以是多个TextView
        SimpleAdapter adapter = new SimpleAdapter(this,mData,android.R.layout.simple_list_item_2,
                new String[]{"fruit","creation"},new int[]{android.R.id.text1,android.R.id.text2});
        ListView listView = (ListView) findViewById(R.id.list_view);
        //装载适配器
        listView.setAdapter(adapter);
    }
}

6.2 效果

Android入门之ListView_第2张图片

7. 自定义ListView界面

7.1 代码

构建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;
    }
}

为ListView的子项指定一个自定义的布局fruit_item.xml ,前两个例子都是用android中内置的布局


    
    


自定义适配器FruitAdapter,继承自ArrayAdapter,将其泛型设置为Fruit
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
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;

/**
 * Created by apple on 2017/5/1.
 */

public class FruitAdapter extends ArrayAdapter{


    private int resourceId;

    public FruitAdapter(Context context, int textViewResourceId, List objects){
      super(context,textViewResourceId, objects);
        resourceId = textViewResourceId;
    }


    //在每个子项被滚动到屏幕内被调用
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//        Fruit fruit = getItem(position);
//        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
//        ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
//        TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
//        fruitImage.setImageResource(fruit.getImageId());
//        fruitName.setText(fruit.getName());
//        return view;


//        提高效率

        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);
        }else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;

    }

    class ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
    }
}

MainActivity中的代码,同时为每个ListView子项添加了点击事件
import android.support.v7.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 {

    private List fruitList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化水果数据
        initFruits();
        //构建适配器
        FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);
        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) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(MainActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initFruits() {
        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }

}

7.2 效果

Android入门之ListView_第3张图片

8. 参考书籍

第一行代码——Android》 郭霖





你可能感兴趣的:(Java,Android)