ListView和RecyclerView的使用和区别

1.ListView的简单用法
activity_main.xml中的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</LinearLayout>

即一个简单的ListView控件
MainActivity.java中的代码:

public class MainActivity extends AppCompatActivity {
    private String[] data = new String[]{"zhangSan","LiSi",
    "ZhaoQian","SunLi","ZhouWu","ZhengWang"};

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

数组中的数据无法直接传递给ListView,需要通过适配器来完成。ArrayAdapter就是一个适配器,可以通过泛型来指定要适配的数据类型,然后在构造函数中把要适配的数据传入。ArrayAdapter有多个构造函数的重载,根据情况选择。这里由于我们提供的数据是String,所以ArrayAdapter的泛型指定为String。然后在ArrayAdapterd的构造函数中依次传入当前上下文,ListView子项布局的id( 这里是一个Android内置的布局文件,里面只有一个TextView),以及要适配的数据。
最后还需要用ListView的setAdapter()方法,将构建好的适配器对象传递进去,这样ListView和数据之间的关联就建立完成了。
运行结果:
在这里插入图片描述
2.自定义ListView的界面
实体类对象Person:

public class Person {
    private String name;
    private int imageId;
    public Person(String name,int imageId){
        this.name = name;
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }

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

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }
}

ListView子项的自定义布局(新建person_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="wrap_content">
    <ImageView
        android:id="@+id/person_image"
        android:layout_width="50dp"
        android:layout_height="50dp" />
    <TextView
        android:id="@+id/person_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="姓名"/>

</LinearLayout>

自定义适配器(PersonAdapter继承自ArrayAdapter)

public class PersonAdapter extends ArrayAdapter<Person> {
    private int resourceId;
    public PersonAdapter(Context context, int textViewResourceId, List<Person> objects){
        super(context,textViewResourceId,objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position,  View convertView, ViewGroup parent) {
        Person person = getItem(position);//获取当前项的Person实例
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);

        ImageView personImage = view.findViewById(R.id.person_image);
        TextView personName = view.findViewById(R.id.person_name);
        personImage.setImageResource(person.getImageId());
        personName.setText(person.getName());

        return view;
    }

}

PersonAdapter重写了父类的一组构造函数,用于将上下文,ListView子项布局id和数据都传递进来。另外又重写了getView()方法,在每个子项被滚动到屏幕内的时候会被调用。在getView()方法,首先调用getItem()方法获得当前项的实例,然后,使用LayoutInflater来为这个子项加载我们传入的布局。
然后View的findViewById()方法分别获取到ImageView和TextView的实例,通过调用setImageResource()和setText()方法来设置显示的图片和文字,最后布局返回。

MainActivity类:

public class MainActivity extends AppCompatActivity {
    private List<Person> personList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPersons();
        PersonAdapter adapter = new PersonAdapter(MainActivity.this,R.layout.person_item,personList);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }
    public void initPersons(){
        for(int i = 0;i < 50;i++){
            Person person = new Person("ZhangSan",R.drawable.timg);
            personList.add(person);
            Person person1 = new Person("LiSi",R.drawable.timg_1);
            personList.add(person1);
            Person person2 = new Person("ZhouWu",R.drawable.timg_2);
            personList.add(person2);
            Person person3 = new Person("ZhaoQian",R.drawable.timg_3);
            personList.add(person3);
            Person person4 = new Person("SunLi",R.drawable.timg_4);
            personList.add(person4);
            Person person5 = new Person("WangEr",R.drawable.timg_5);
        }
    }
}

initPersons方法用于初始化personList的数据,adapter创建和之前一样,传入参数,最后setAdapter()方法传入adopter。
运行结果:
在这里插入图片描述
3.提升ListView的运行效率
两个方面提高效率,加载布局的效率和初始化实例的效率
PersonAdapter中的getView方法修改:

    @Override
    public View getView(int position,  View convertView, ViewGroup parent) {
        Person person = getItem(position);//获取当前项的Person实例
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.personImage = view.findViewById(R.id.person_image);
            viewHolder.personTextView = view.findViewById(R.id.person_name);
            view.setTag(viewHolder);//将ViewHolder存储到View中
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.personImage.setImageResource(person.getImageId());
        viewHolder.personTextView.setText(person.getName());

//        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
//
//        ImageView personImage = view.findViewById(R.id.person_image);
//        TextView personName = view.findViewById(R.id.person_name);
//        personImage.setImageResource(person.getImageId());
//        personName.setText(person.getName());

        return view;
    }
    class ViewHolder{
        ImageView personImage;
        TextView personTextView;
    }

如果convertView为null,使用LayoutInflater去加载布局;不为null,则直接对convertView进行重用。
内部类ViewHolder,实现对数据的缓冲。当convertView为null时,创建ViewHolder实例,将控件的实例都存放在ViewHolder中,调用View的setTag()方法,将ViewHolder的对象存储在View中。当convertView不为null时,调用view的getTag()方法,把ViewHolder重新取出。
4.ListView的点击事件
setOnItemClickListener方法
MainActivity代码:

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Person person = personList.get(position);
                Toast.makeText(MainActivity.this,person.getName(),Toast.LENGTH_SHORT).show();

            }
        });

6.RcyclerView的简单用法
首先需要在app/build.gradle文件,dependencies闭包中添加依赖:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

将person_item.layout和person类拷贝至新工程,省的代码重写。
新建PersonAdapter类,继承RecyclerView.Adapter, 并将范类指定为Person.ViewHolder(内部类)

PersonAdapter类

public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolder> {

    private List<Person> mPersonList;
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView personImage;
        TextView personText;
        public ViewHolder(View view){
            super(view);
            personImage = view.findViewById(R.id.person_image);
            personText = view.findViewById(R.id.person_name);

        }
    }
    public PersonAdapter(List<Person> personList){
        mPersonList = personList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.person_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Person person = mPersonList.get(position);
        holder.personImage.setImageResource(person.getImageId());
        holder.personText.setText(person.getName());
    }

    @Override
    public int getItemCount() {
        return mPersonList.size();
    }
}

内部类ViewHolder,构造函数传入View参数,这个参数通常是ReyeclerView子项的最外层布局,通过findViewById()方法可以获取布局的ImageView和TextView实例。
PersonAdapter中也有一个构造函数,用于把要展示的数据源传进来,赋值给全局变量mPersonList。
重写onCreateViewHolder方法,创建ViewHolder实例,将person_item布局加载到构造函数中,最后把ViewHolder实例返回。
重写onBindViewHolder方法,对子项数据进行赋值初始化。
重写getItemCount()方法,返回数据源的长度。
MainActivity类:

public class MainActivity extends AppCompatActivity {
    private List<Person> personList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPersons();
        RecyclerView recyclerView = findViewById(R.id.reyecler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        PersonAdapter adapter = new PersonAdapter(personList);
        recyclerView.setAdapter(adapter);

    }
    public void initPersons(){
        for(int i = 0;i < 50;i++){
            Person person = new Person(" ZhangSan",R.drawable.timg);
            personList.add(person);
            Person person1 = new Person("LiSi",R.drawable.timg_1);
            personList.add(person1);
            Person person2 = new Person("ZhouWu",R.drawable.timg_2);
            personList.add(person2);
            Person person3 = new Person("ZhenSan",R.drawable.timg_3);
            personList.add(person3);
            Person person4 = new Person("SunSi",R.drawable.timg_4);
            personList.add(person4);
            Person person5 = new Person("QianLiu",R.drawable.timg_5);
            personList.add(person5);
        }

    }
}

获取ReyeclerView对象,然后创建一个LinearLayoutManager对象(线性布局),设置到ReyeclerView对象中。然后获取PersonAdapter实例,将数据传入构建方法,最后ReyeclerView对象实现setAdaper方法传入PersonAdatper实例。

7.实现横向滚动,瀑布流和表格布局
横向滚动:
新建子项布局person_item_2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/person_image_2"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"/>
    <TextView
        android:id="@+id/person_name_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>


</LinearLayout>

PersonAdapter中的相应控件名称进行修改。
最重要的是修改MainActivity中的LinearLayoutManager设置。

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPersons();
        RecyclerView recyclerView = findViewById(R.id.reyecler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);//线性布局
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        PersonAdapter adapter = new PersonAdapter(personList);
        recyclerView.setAdapter(adapter);

    }

通过LinearLayoutManager的setOrientation()方法来设置布局的排列方向。
运行结果:
在这里插入图片描述

瀑布流布局:

新建子项布局person_item_3.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"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/person_image_3"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"/>

    <TextView
        android:id="@+id/person_name_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>

LinearLayout的宽度改成了match_parent,因为瀑布流布局的宽度是根据布局列数在适配的,不是固定值。

PersonAdapter中的相应控件名称进行修改。
最重要的是修改MainActivity中的StaggeredGridLayoutManager设置。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPersons();
        RecyclerView recyclerView = findViewById(R.id.reyecler_view);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this);//线性布局
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //瀑布布局
        StaggeredGridLayoutManager staggeredGridLayoutManager = new
                StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        PersonAdapter adapter = new PersonAdapter(personList);
        recyclerView.setAdapter(adapter);

    }

StaggeredGridLayoutManager的构造函数接收2个参数,第一个是指定布局的列数,第二个是布局的排列方向。
运行结果:
在这里插入图片描述
表格布局:

新建子项布局person_item_4.xml:

<<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
    <ImageView
        android:id="@+id/person_image_4"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"/>
    <TextView
        android:id="@+id/person_name_4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>

PersonAdapter中的相应控件名称进行修改。
最重要的是修改MainActivity中的GridLayoutManager 设置。

public class MainActivity extends AppCompatActivity {
    private List<Person> personList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initPersons();
        RecyclerView recyclerView = findViewById(R.id.reyecler_view);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this);//线性布局
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        //瀑布布局
//        StaggeredGridLayoutManager staggeredGridLayoutManager = new
//                StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        GridLayoutManager gridLayoutManager = new GridLayoutManager
                (this,5);
        recyclerView.setLayoutManager(gridLayoutManager);
        PersonAdapter adapter = new PersonAdapter(personList);
        recyclerView.setAdapter(adapter);

    }

GridLayoutManager 的构造函数接收2个参数,第一个是布局,第二个是指定布局的列数。
运行结果:在这里插入图片描述
8.RecyclerView的点击事件
在子项具体的View中去注册点击事件。
PersonAdapter代码:

public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolder> {

    private List<Person> mPersonList;
    static class ViewHolder extends RecyclerView.ViewHolder{
        View personView;
        ImageView personImage;
        TextView personText;
        public ViewHolder(View view){
            super(view);
            personView = view;
            personImage = view.findViewById(R.id.person_image_4);
            personText = view.findViewById(R.id.person_name_4);

        }
    }
    public PersonAdapter(List<Person> personList){
        mPersonList = personList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.person_item_4,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        holder.personView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              int position = holder.getAdapterPosition();
              Person person = mPersonList.get(position);
                Toast.makeText(v.getContext(),person.getName(),Toast.LENGTH_SHORT).show();
            }
        });
        holder.personImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Person person = mPersonList.get(position);
                Toast.makeText(v.getContext(),person.getName(),Toast.LENGTH_SHORT).show();;
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Person person = mPersonList.get(position);
        holder.personImage.setImageResource(person.getImageId());
        holder.personText.setText(person.getName());
    }

    @Override
    public int getItemCount() {
        return mPersonList.size();
    }
}

修改了ViewHolder,在ViewHolder中添加了personView变量来保存子项最外层布局的实例,然后在onCreateViewHolder()方法中注册点击事件就可以。这里我们将最外层布局和图片控件注册了点击事件,先获取点击的position,通过position得到实例,Toast实例的姓名。
9.ListView和RecycleView的区别:
1)ListView布局单一,RecycleView可以根据LayoutManger有横向,瀑布和表格布局
2)自定义适配器中,ListView的适配器继承ArrayAdapter;RecycleView的适配器继承RecyclerAdapter,并将范类指定为子项对象类.ViewHolder(内部类)。
3)ListView优化需要自定义ViewHolder和判断convertView是否为null。 而RecyclerView是存在规定好的ViewHolder。
4)绑定事件的方式不同,ListView是在主方法中ListView对象的setOnItemClickListener方法;RecyclerView则是在子项具体的View中去注册事件。
参考:
《第一行代码》
两者区别具体看:https://blog.csdn.net/shu_lance/article/details/79566189

  • 17
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值