Android UI篇——ListView

Android UI篇——ListView

ListView是一个用来纵向显示条目的视图,这些条目内容来自于与该ListView相关联的ListAdapter.

ListView的简单用法

先新建一个项目吧!

创建了主活动MainActivity后,我们修改在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>

这其实就是在活动的布局中加入了一个占满屏幕的List View控件并为他起了一个id;

接下来修改MainActivity中的代码:

package com.example.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private String[] data = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    @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);
    }
}

我们提前将英文字母表做成字符串数组,通过适配器adapter然后传入到ListView中就可以了。

这里我们需要注意,数组中的数据是无法直接传入到ListView中的,我们需要借助适配器来完成这些操作。安卓提供了许多适配器的种类,这里ArraryAdapter只是其中一种,ArrayAdapter的构造函数依次传入的是当前上下文,List View的子项布局,适配的数据这三个东西。然后通过调用LisstView的setAdapter()方法,将适配器对象传入到List View中,这样就建立了ListView和数据的连接。

最后我们运行程序,结果如下图:

定制ListView的界面

只有文字的显示用户肯定会觉得很low,所以我们如果想添加更多的元素该怎么办?

这里我用葫芦七兄弟做一个演示。

我们先定义一个实体类Brothers,这个要用来作为ListView适配器适配的数据。

package com.example.listviewtest;

public class Brothers {
    private String name;
    private int imageId;

    public Brothers(String name,int imageId){
        this.imageId = imageId;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

这里定义的类只有图片和文字两个控件,所以我们与要创建一个新的适配器子项布局来对应,我们将其命名为brothers_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/brothers_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/brothers_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textSize="18sp"/>

</LinearLayout>

在这个布局中我们定义了一个Image View用于显示图片,TextView用于显示葫芦娃的名字。

接下来我们就要创建属于自己的适配器BrothersAdapter来接受葫芦兄弟的数据,这个适配器继承ArrayAdapter,并且泛型为我们的自定义类Brothers,代码如下:

package com.example.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.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class BrothersAdapter extends ArrayAdapter<Brothers> {

    private int resourceId;

    public BrothersAdapter(Context context, int textViewResourceId, List<Brothers> brothers){
        super(context , textViewResourceId , brothers);
        this.resourceId = textViewResourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Brothers brother = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        ImageView brotherImage = view.findViewById(R.id.brothers_image);
        TextView brotherText = view.findViewById(R.id.brothers_name);
        brotherImage.setImageResource(brother.getImageId());
        brotherText.setText(brother.getName());
        return view;
    }
}

最后我们修改MainActivity中的代码:

package com.example.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {

    private List<Brothers> brothersList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBrothers();
        BrothersAdapter adapter = new BrothersAdapter(MainActivity.this,R.layout.brothers_item,brothersList);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }

    private void initBrothers(){
        Brothers dawa = new Brothers("我是大娃",R.drawable.dawa);
        brothersList.add(dawa);
        Brothers erwa = new Brothers("我是二娃",R.drawable.erwa);
        brothersList.add(erwa);
        Brothers sanwa = new Brothers("我是三娃",R.drawable.sanwa);
        brothersList.add(sanwa);
        Brothers siwa = new Brothers("我是四娃",R.drawable.siwa);
        brothersList.add(siwa);
        Brothers wuwa = new Brothers("我是五娃",R.drawable.wuwa);
        brothersList.add(wuwa);
        Brothers liuwa = new Brothers("我是六娃",R.drawable.liuwa);
        brothersList.add(liuwa);
        Brothers qiwa = new Brothers("我是七娃",R.drawable.qiwa);
        brothersList.add(qiwa);
    }
}

接下来我们运行看一下效果图吧:

提升ListView的运行效率

虽然上面的代码可以完成我们需要做到的效果,不过它还是有缺点的:它的运行效率非常低,因为在我们的BrothersAdapter中的getView()方法中我们每次都将布局重新加载一遍,当ListView快速滚动的时候,这就成为了性能的瓶颈。

我们可以看到getView()方法中还有一个contertView参数,这个参数用于将之前加载好的布局进行缓存,以便于后面用它。

所以我们修改BrothersAdapter中的代码:

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Brothers brother = getItem(position);
        View view;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        }else{
            view = convertView;
        }
        ImageView brotherImage = view.findViewById(R.id.brothers_image);
        TextView brotherText = view.findViewById(R.id.brothers_name);
        brotherImage.setImageResource(brother.getImageId());
        brotherText.setText(brother.getName());
        return view;
    }

我们在getView()方法中进行了判断,如果convertView为null,我们就使用LayoutInflater去加载布局,如果不为null的话,我们就直接使用convertView进行重用。这样我们就很大地提高了ListView的运行效率。

虽然我们不会再重复的去加载布局了,不过我们每次在getView()中还是会调用View的findViewById()方法来获取一次控件的实例。我们可以接著一个ViewHolder来对这部分性能进行优化,我们再次修改BrothersAdapter中的代码:

package com.example.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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.List;

public class BrothersAdapter extends ArrayAdapter<Brothers> {

    private int resourceId;

    public BrothersAdapter(Context context, int textViewResourceId, List<Brothers> brothers){
        super(context , textViewResourceId , brothers);
        this.resourceId = textViewResourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Brothers brother = getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.brotherImage = view.findViewById(R.id.brothers_image);
            viewHolder.brotherText = view.findViewById(R.id.brothers_name);
            view.setTag(viewHolder);
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.brotherImage.setImageResource(brother.getImageId());
        viewHolder.brotherText.setText(brother.getName());
        return view;
    }
    
    class ViewHolder{
        
        ImageView brotherImage;
        
        TextView brotherText;
        
    }
}

我们在BrothersAdapter中新增了一个内部类ViewHolder,用于对控件的实例进行缓存。如果conterView为null,我们就把所有获取到控件的实例存放在ViewHolder里,然后调用View的setTag()方法,将ViewHolder对象储存在View中。当conterView不为null的时候,就用view的getTag()方法,把ViewHolder取出来,这样我们就不用每次都用findViewById()方法来获取控件实例。

ListView的点击事件

ListView点击事件的实质是分别为每个子项创建了点击事件,下面我们通过代码来看下怎么实现:

package com.example.listviewtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class MainActivity extends AppCompatActivity {

    private List<Brothers> brothersList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initBrothers();
        BrothersAdapter adapter = new BrothersAdapter(MainActivity.this,R.layout.brothers_item,brothersList);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
			@Override
			public void onItemClick(Adapter<?> parent, View view, int position, long id){
				Brothers brothers = brothersList.get(position);
				Toast.makeText(MainActivity.this, brothers.getName(),Toast.LENGTH_SHORT).show();
				}
			});
    }	

    private void initBrothers(){
        Brothers dawa = new Brothers("我是大娃",R.drawable.dawa);
        brothersList.add(dawa);
        Brothers erwa = new Brothers("我是二娃",R.drawable.erwa);
        brothersList.add(erwa);
        Brothers sanwa = new Brothers("我是三娃",R.drawable.sanwa);
        brothersList.add(sanwa);
        Brothers siwa = new Brothers("我是四娃",R.drawable.siwa);
        brothersList.add(siwa);
        Brothers wuwa = new Brothers("我是五娃",R.drawable.wuwa);
        brothersList.add(wuwa);
        Brothers liuwa = new Brothers("我是六娃",R.drawable.liuwa);
        brothersList.add(liuwa);
        Brothers qiwa = new Brothers("我是七娃",R.drawable.qiwa);
        brothersList.add(qiwa);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值