一、直接在布局文件中使用ListView
1、布局文件
- 1 <?xml version="1.0" encoding="utf-8"?>
- 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- 3 xmlns:tools="http://schemas.android.com/tools"
- 4 android:layout_width="match_parent"
- 5 android:layout_height="match_parent"
- 6 tools:context=".MainActivity">
- 7
- 8 <ListView
- 9 android:id="@+id/lv_list"
- 10 android:layout_width="match_parent"
- 11 android:layout_height="match_parent" />
- 12
- 13 </RelativeLayout>
2、填充ListView代码
- 1 package com.ietree.listviewdemo;
- 2
- 3 import androidx.appcompat.app.AppCompatActivity;
- 4
- 5 import android.os.Bundle;
- 6 import android.view.View;
- 7 import android.view.ViewGroup;
- 8 import android.widget.BaseAdapter;
- 9 import android.widget.ListAdapter;
- 10 import android.widget.ListView;
- 11 import android.widget.TextView;
- 12
- 13 public class MainActivity extends AppCompatActivity {
- 14 private ListView lv_list;
- 15
- 16 @Override
- 17 protected void onCreate(Bundle savedInstanceState) {
- 18 super.onCreate(savedInstanceState);
- 19 setContentView(R.layout.activity_main);
- 20
- 21 // 获取ListView控件
- 22 lv_list = findViewById(R.id.lv_list);
- 23 // 给ListView控件设置自定义适配器
- 24 lv_list.setAdapter(new MyAdapter());
- 25 }
- 26
- 27 /**
- 28 * 定义一个适配器
- 29 */
- 30 private class MyAdapter extends BaseAdapter {
- 31 // 返回需要显示的条目数
- 32 @Override
- 33 public int getCount() {
- 34 return 100;
- 35 }
- 36
- 37 @Override
- 38 public Object getItem(int position) {
- 39 return null;
- 40 }
- 41
- 42 @Override
- 43 public long getItemId(int position) {
- 44 return 0;
- 45 }
- 46
- 47 /**
- 48 * 获取一个View用来显示ListView的数据,会作为ListView的一个条目显示
- 49 * @param position 当前需要显示的View的索引
- 50 * @param convertView 或存数据的对象
- 51 * @param parent
- 52 * @return 返回需要显示的View
- 53 */
- 54 @Override
- 55 public View getView(int position, View convertView, ViewGroup parent) {
- 56 TextView textView = new TextView(MainActivity.this);
- 57 textView.setText("这是第" + position + "个TextView");
- 58 return textView;
- 59 }
- 60 }
- 61 }
3、结果显示

4、几个需要注意的问题
1、ListView的布局不建议使用
原因:
假如我们需要显示5个item,在使用 android:layout_height="wrap_content"的布局情况下,getView()方法会被调用9次,原因是他需要计算需要多少个item把当前界面填满,所以会循环调用多次。


但是如果使用 android:layout_height="match_parent" ,getView()方法就最多被调用5次。所以,一般推荐item在布局时使用android:layout_height="match_parent" 减少重复调用次数。

2、假如需要显示的item有10000个,使用上面的每加载一个item就要新生成一个TextView对象的方法,会导致在滑动过程中加载内容过多导致卡顿或者内存溢出的情况,所以需要复用TextView对象。改造过后如下:
- /**
- * 获取一个View用来显示ListView的数据,会作为ListView的一个条目显示
- *
- * @param position 当前需要显示的View的索引
- * @param convertView 或存数据的对象
- * @param parent
- * @return 返回需要显示的View
- */
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView textView = null;
- if (convertView == null) {
- System.out.println("创建新对象");
- textView = new TextView(MainActivity.this);
- } else {
- System.out.println("复用老对象");
- textView = (TextView) convertView;
- }
- textView.setText("这是第" + position + "个TextView");
- return textView;
- }
结果如下:
