Control of the ListView Android

Android controls many as the most basic TextView, Button, click on it with their own grasp. Today, we give everyone talking ListView.

Among the many Android ListView control possession more important position, it allows the user to scroll off-screen data into the screen by sliding up and down, while the original data in the screen scroll off the screen to display more data content. ListView control is one of the hottest, most platitudes about him is that performance optimization.

Three elements

ListView: for example shows a list ListView
data set: the string is mapped pictures
Adapter (data adapter): used to map the data into the ListView

如果响应事件,还要为ListView注册监听器:setOnItemClivkListener(OnItemClivkListener)

Adapter Adapter

简单理解就是adapter是view和数据的桥梁。在一个ListView或者GridView中,你不可能手动给每一个格子都新建一个view,所以这时候就需要Adapter的帮忙,它会帮你自动绘制view并且填充数据。

adapter Type:

  • ArrayAdapter
  • BaseAdapter
  • CursorAdapter
  • HeaderViewAdapter
  • ResourceCursorAdapter
  • SimpleAdapter
  • SimpleCursorAdapter
  • WrapperListAdapter

The most commonly used are the following three

ArrayAdapter、SimpleAdapter、BaseAdapter

ArrayAdapter use

Results are as follows:
Here Insert Picture Description

GitHub download

1. Add a ListView control in the activity_main.xml

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

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

</LinearLayout>

2, create a new layout item_layout.xml (also can use the system comes with layout), which is written in the list each item contained controls
Here Insert Picture Description
Here Insert Picture Description

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#111"
    android:textSize="30dp" />

3, ListView control MainActivity acquired by the display data to the Adapter the ListView

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

                          //苹果     香蕉      橘子       西瓜          梨      葡萄      菠萝(凤梨)    草莓          樱桃      芒果
        String[] data = {"apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
                "apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
                "apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango"};

        //获取ListView
        ListView lv = findViewById(R.id.lv);

        /**
         * 敲黑板,划重点
         * 创建adapter
         * 参数1 当前上下文环境
         * 参数2 当前引用的布局,可以用系统默认,也可以根据需求使用自己写的
         * 参数3 当前绑定的数据
         */
        //用自定义的布局文件
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.item_layout, data);
        //用系统的布局文件
        //ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);

        //将数据和布局关联,就是将数据显示到列表中
        lv.setAdapter(adapter);
    }

SimpleAdapter use

Results as shown below: 因为添加数据比较麻烦,所以本人只添加了四条数据(小羞愧),如果数据足够多的话,是可以滑动的
Here Insert Picture Description
GitHub Codes

1. Add a ListView control in the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

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

</android.support.constraint.ConstraintLayout>

2, create a new layout item_layout.xml (also can use the system comes with layout), which is written in the list each item contained controls

<?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"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp" />
</LinearLayout>

3, ListView control MainActivity acquired by the display data to the Adapter the ListView

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

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

        //构造数据
        Map<String, Object> map = new HashMap<>();
        map.put("pic", R.drawable.pineapple);
        map.put("name", "pineapple");
        fruits.add(map);

        Map<String, Object> map1 = new HashMap<>();
        map1.put("pic", R.drawable.grape);
        map1.put("name", "grape");
        fruits.add(map1);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("pic", R.drawable.cherry);
        map2.put("name", "cherry");
        fruits.add(map2);

        Map<String, Object> map3 = new HashMap<>();
        map3.put("pic", R.drawable.strawberry);
        map3.put("name", "strawberry");
        fruits.add(map3);

        /**
         * 敲黑板,划重点
         * 创建适配器
         * 参数1:Context:上下文对象
         * 参数2:data要关联的数据源
         * 参数3:resources:子项布局
         * 参数4:from:数据源的关键字名称的数组
         * 参数5:to:显示数据源各子项值的控件id
         */
        SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this,
                fruits,
                R.layout.item_layout,
                new String[]{"pic", "name"},
                new int[]{R.id.image, R.id.name});
        //获取ListView
        ListView lv = findViewById(R.id.lv);
        //将数据和布局关联,就是将数据显示到列表中
        lv.setAdapter(simpleAdapter);
    }

BaseAdapter use

Effect:
Here Insert Picture Description
GitHub download

1. Add a ListView control in the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

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

</android.support.constraint.ConstraintLayout>

2, create a new layout item_layout.xml (also can use the system comes with layout), which is written in the list each item contained controls

<?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"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp" />
</LinearLayout>

3, write a class that inherits from BaseAdapter class, and to achieve BaseAdapter four a few basic methods:

  1. The number of data sets filled getCount
  2. getItem data set corresponding to the specified index data items
  3. getItemId specified row corresponding to the ID
  4. getView each Item class content displayed
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 java.util.List;

/**
 * 敲黑板,划重点
 */
public class TestAdapter extends BaseAdapter {
    private final int resourceId;//页面布局
    private Context mContext;//上下文
    private List<Fruit> data;//数据源

    public TestAdapter(Context context, int resourceId, List<Fruit> data) {
        this.mContext = context;
        this.resourceId = resourceId;
        this.data = data;
    }

    //数据源的长度,也就是ListView要显示多少条数据,我们就传入多长的数据源就可以了
    @Override
    public int getCount() {
        return data.size();
    }

    //获取每一条数据的位置
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    //获取每一项的id
    @Override
    public long getItemId(int position) {
        return position;
    }

    //显示出数据源中的每一条数据
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(mContext).inflate(resourceId, null);
        ImageView image = view.findViewById(R.id.image);
        TextView name = view.findViewById(R.id.name);
        image.setImageResource((Integer) data.get(position).getPic());
        name.setText(data.get(position).getName());
        return view;
    }
}

4, create a Fruit class, which has name, pic two properties

class Fruit {
    private String name;
    private Object pic;

    public Fruit(String name, Object pic) {
        this.name = name;
        this.pic = pic;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getPic() {
        return pic;
    }

    public void setPic(Object pic) {
        this.pic = pic;
    }

    @Override
    public String toString() {
        return "Fruit{" +
                "name='" + name + '\'' +
                ", pic=" + pic +
                '}';
    }
}

5, in the display data to the LIstView

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

        ListView lv = findViewById(R.id.lv);

        //构造数据
        final List<Fruit> fruits = new ArrayList();
        for (int i = 0; i < 10; i++) {
            fruits.add(new Fruit("菠萝", R.drawable.pineapple));
            fruits.add(new Fruit("葡萄", R.drawable.grape));
            fruits.add(new Fruit("樱桃", R.drawable.cherry));
            fruits.add(new Fruit("草莓", R.drawable.strawberry));
        }

        /**
         * 创建自己定义的适配器
         * parameter1:上下文
         * parameter2:ListView每一项的页面布局
         * parameter3:数据源
         */
        TestAdapter testAdapter = new TestAdapter(MainActivity.this, R.layout.item_layout, fruits);
        //关联数据
        lv.setAdapter(testAdapter);

        //添加点击事件监听
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,
                        "您选择了" + fruits.get(position).getName(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

Alas Calls Xi, so much today, optimization problems later and share.

Published 86 original articles · won praise 90 · views 180 000 +

Guess you like

Origin blog.csdn.net/engerla/article/details/105312958