Android listview

Time:2021-6-15

Listview is one of the most commonly used controls in Android. Almost all applications use it, so it is very important to learn to use it. Now let’s understand the usage of listview from an example. Let’s take a look at the project structure diagram of our example

image

Here we first look at fruit, fruit adapter and fruit_ Item

Fruit is a type that acts as a listview adapter

Fruitadapter is an adapter that inherits arrayadapter

fruit_ Item is the child layout file of listview

So the question is, why is there 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 kind of Android which is easy to use. You can specify the data type to be adapted through generics, and then pass the data to be adapted into the constructor

Now 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 is used to store data
    private List fruitList=new ArrayList<>();

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

        //First get the data and put it on the adapter
        initFruits(); // Initialize fruit data
        FruitAdapter adapter=new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);

        //Pass the data on the adapter to listview
        ListView listView=findViewById(R.id.list_view);
        listView.setAdapter(adapter);

        //Register a listener for the listview. When the user clicks any sub item in the listview, it will call back the onitemclick() method
        //In this method, the position parameter can be used to determine which sub item the user clicks
        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();
            }
        });
    }

    //Initialization data
    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. Just look at the comments

Let’s take a look at the corresponding activity_ The code of main.xml

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 adapter, fruitadapter

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 {
    private int resourceId;

    //The constructor of the adapter passes the data to be adapted here
    public FruitAdapter(Context context, int textViewResourceId, List objects){
        super(context,textViewResourceId,objects);
        resourceId=textViewResourceId;
    }

    //The convertview parameter is used to cache the previously loaded layout
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        Fruit fruit=getItem(position); // Gets the fruit instance of the current item

        //Add a judgment to avoid reloading the layout every time the listview scrolls, so as to improve the running efficiency
        View view;
        ViewHolder viewHolder;
        if (convertView==null){

            //Avoid reloading the layout every time the listview scrolls to improve the efficiency
            view=LayoutInflater.from(getContext()).inflate(resourceId,parent,false);

            //Avoid getting control instances again every time getview() is called
            viewHolder=new ViewHolder();
            viewHolder.fruitImage=view.findViewById(R.id.fruit_image);
            viewHolder.fruitName=view.findViewById(R.id.fruit_name);

            //Store viewholder in view (that is, the instance of the control in it)
            view.setTag(viewHolder);
        } else{
            view=convertView;
            viewHolder=(ViewHolder) view.getTag();
        }

        //Get the instance of the control and call the set... Method to display it
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
        return view;
    }

    //Define an internal class to cache the instance of the control
    class ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    }
}

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

Now let’s look at the fruit 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

Looking at the code in this line of fruitadapter, we use fruit as the type of adapter

Let’s take a final look at fruit_ Code of item

The code is not complicated, and each subitem layout displays a picture and a piece of text

The final picture is as follows:

image

Conclusion:
The key to using listview is to master the adapter and the type of adapter, and then you can customize your own listview interface. Listview is powerful, but it can only achieve the effect of vertical scrolling. If you want to achieve horizontal scrolling, you will be powerless.

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]