Android listview

Listview is one of the most commonly used controls in Android. It is used by almost all applications, so it is important to learn to use it. Let's understand the usage of listview from an example. Let's take a look at the project structure diagram of our example first

Let's look at fruit, fruit adapter and fruit first_ Item these three files

So the question is, why do you have an adapter? What is its function?

The reason why we need an adapter is that our data cannot be directly transferred to listview, so we need to use the adapter to complete the data transfer. Arrayadapter is a more useful one in Android. You can specify the data type to be adapted through generics, and then pass the data to be adapted into the constructor

Let's take a look at the code of each part. First, let's take a look at the code of mainactivity

package com.example.apple.listviewtest;

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 {

    // fruitList用于存储数据
    private List<Fruit> 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注册一个监听器,当用户点击了ListView中的任何一个子项时,就会回调onItemClick()方法
        // 在这方法中可以通过position参数判断出用户点击的是那一个子项
        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<10;i++){
            Fruit a=new Fruit("a",R.drawable.a);
            fruitList.add(a);
            Fruit b=new Fruit("B",R.drawable.b);
            fruitList.add(b);
            Fruit c=new Fruit("C",R.drawable.c);
            fruitList.add(c);
            Fruit d=new Fruit("D",R.drawable.d);
            fruitList.add(d);
        }
    }
}

The code is not complicated. Let's just look at the comments directly

Next, take a look at the corresponding activity_ Code for main.xml

<?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"
    >

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

The code here is also very simple, that is, a listview control is used

Then let's take a look at the code of the fruitadapter adapter

package com.example.apple.listviewtest;


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 FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;

    // 适配器的构造函数,把要适配的数据传入这里
    public FruitAdapter(Context context,int textViewResourceId,List<Fruit> objects){
        super(context,textViewResourceId,objects);
        resourceId=textViewResourceId;
    }

    // convertView 参数用于将之前加载好的布局进行缓存
    @Override
    public View getView(int position,View convertView,ViewGroup parent){
        Fruit fruit=getItem(position); //获取当前项的Fruit实例

        // 加个判断,以免ListView每次滚动时都要重新加载布局,以提高运行效率
        View view;
        ViewHolder viewHolder;
        if (convertView==null){

            // 避免ListView每次滚动时都要重新加载布局,以提高运行效率
            view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false);

            // 避免每次调用getView()时都要重新获取控件实例
            viewHolder=new ViewHolder();
            viewHolder.fruitImage=view.findViewById(R.id.fruit_image);
            viewHolder.fruitName=view.findViewById(R.id.fruit_name);

            // 将ViewHolder存储在View中(即将控件的实例存储在其中)
            view.setTag(viewHolder);
        } else{
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }

        // 获取控件实例,并调用set...方法使其显示出来
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }

    // 定义一个内部类,用于对控件的实例进行缓存
    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}

You can see that in the fruitadapter class, we have overridden a set of constructors of the parent class to pass in the context, the ID and data of the listview child layout. In addition, it rewrites the getview () method, which will be called when each sub item is scrolled to the screen. The operation efficiency of listview itself is very low, so we need to optimize. The specific optimization method is already in the code. Just look at the code comments directly

Now let's look at fruit's code

package com.example.apple.listviewtest;

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

Fruit is the type of listview adapter, that is, the type of data passed into listview.

public class FruitAdapter extends ArrayAdapter<Fruit>

Look at this line of code in fruit adapter. We use fruit as the type of adapter

Let's take a final look at fruit_ Code of 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">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"
        />
</LinearLayout>

The code is not complex. Each sub item layout displays a picture and a paragraph of text

The final effect drawing is as follows:

Summary: the key to using listview is to master the adapter and the type of adapter. After mastering these two aspects, you can basically customize your own listview interface. Although listview is powerful, it can only achieve the effect of vertical scrolling. If you want to achieve horizontal scrolling, you have no intention.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>