Android studio 最常用的控件ListView

时间:2024-03-30 20:58:29

ListView 可以算是最常用的控件之一了,由于屏幕控件有限,当我们有大量的数据需要展示的时候,就要借助ListView来实现,通过屏幕滚动的方式来展示数据

我们先建立一个ListViewTest项目,然后修改activity_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>

接着修改MainActivity中的代码

package com.example.listview;

import android.support.v7.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;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


   private String[] data = {"apple","bannner","orange","watermelon","pear","grape",
           "pineapple","strawberry","cherry","mango","apple","bannner","orange",
          "watermelon","pear","grape", "pineapple","strawberry","cherry","mango"
   };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
         MainActivity.this,android.R.layout.simple_list_item_1,data);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);//把构造好的适配器对象传进去

     
    }

这里我们简单的设置一个data数组作为数据源,数组中的数据是无法直接传递给ListView的,我们需要借助适配器来完成,我觉得Android中最好用的就是ArrayAdapter,可以通过泛型来指定要适配的数据类型,在构造函数中把数据传入,android.R.layout.simple_list_item_1是一个内置的布局文件,一个最简单的ListView就做好了

~~---------------------------------------------------------------------------------------------------------------------~

很多时候我们实际应用中都不能只是一段文本,还有图片,接下来我们来给ListView加上图片和点击事件
首先定义一个实体类,作为ListView适配器的适配类型,新建类Fruit

package com.example.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

<?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">
<ImageView
    android:id="@+id/fruit_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<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>

然后自定义一个适配器,新建类FruitAdapter

package com.example.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 FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;
//重写构造函数,把id和数据传进来
    public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Fruit fruit = getItem(position);//获取当前项的Fruit实例
      /* View view = LayoutInflater.from
                (getContext()).inflate(resourceId, parent, false);
        
        */
      //对上一个语句进行优化
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);//false参数表示只让我们在父布局中声明的layout属性生效
        }else {
            view = convertView;
        }
        ImageView fruitImage = view.findViewById(R.id.fruit_image);
        TextView fruitName = view.findViewById(R.id.fruit_name);

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

    }
}

最后修改MainActivity

package com.example.listview;

import android.support.v7.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;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();

   /*private String[] data = {"apple","bannner","orange","watermelon","pear","grape",
           "pineapple","strawberry","cherry","mango","apple","bannner","orange",
          "watermelon","pear","grape", "pineapple","strawberry","cherry","mango"
   };*/

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


        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        //  MainActivity.this,android.R.layout.simple_list_item_1,data);
        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_LONG).show();
            }
        });
    }
    private void initFruits() {
        for(int i = 0;i<2;i++){//循环两遍,只添加一遍的话不足以充满屏幕
            Fruit apple = new Fruit("apple",R.drawable.ic_launcher_background);//这里懒得找图片了,直接用系统图片
            fruitList.add(apple);
            Fruit banana = new Fruit("banana",R.drawable.ic_launcher_background);
            fruitList.add(banana);
            Fruit orange = new Fruit("orange",R.drawable.ic_launcher_background);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("watermelon",R.drawable.ic_launcher_background);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("pear",R.drawable.ic_launcher_background);
            fruitList.add(pear);
            Fruit grape = new Fruit("grape",R.drawable.ic_launcher_background);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("pineapple",R.drawable.ic_launcher_background);
            fruitList.add(pineapple);
            Fruit cherry = new Fruit("cherry",R.drawable.ic_launcher_background);
            fruitList.add(cherry);
            Fruit mango = new Fruit("mango",R.drawable.ic_launcher_background);
            fruitList.add(mango);
        }

    }

}
  • 最后我们来运行一下效果

Android studio 最常用的控件ListView