前言:
ListView这个列表控件在Android中是最常用的控件之一,几乎在所有的应用程序中都会使用到它。
目前正在做的一个记账本APP中就用到了它,主要是用它来呈现收支明细,是一个图文列表的呈现方式,下面就讲讲具体是如何实现的。
效果图:
该功能是在另一篇博文【Android Studio 使用ViewPager + Fragment实现滑动菜单Tab效果 --简易版】的基础上进行添加的

实现的思路:
1、该功能是用fragment来做布局的,首先创建一个fragment.xml布局文件,在里面添加一个ListView控件;
2、由于List里面既要呈现图片,也要呈现文字,所以再创建一个fragment_item.xml布局文件,在里面添加ImageView、TextView,用来显示图片和文字;
3、使用SimpleAdapter来绑定数据;
具体实现逻辑:
1、创建fragment_one.xml
- 1 <ListView
- 2 android:id="@+id/lv_expense"
- 3 android:layout_width="match_parent"
- 4 android:layout_height="wrap_content">
- 5
- 6 </ListView>
2、创建fragment_one_item.xml
- 1 <ImageView
- 2 android:id="@+id/image_expense"
- 3 android:layout_width="wrap_content"
- 4 android:layout_height="wrap_content"
- 5 android:paddingTop="10dp"
- 6 android:paddingRight="10dp"
- 7 android:paddingBottom="10dp"
- 8 android:adjustViewBounds="true"
- 9 android:maxWidth="72dp"
- 10 android:maxHeight="72dp"/>
- 11 <TextView
- 12 android:id="@+id/tv_expense_category"
- 13 android:layout_width="wrap_content"
- 14 android:layout_height="wrap_content"
- 15 android:layout_weight="1"
- 16 android:padding="10dp"/>
- 17 <TextView
- 18 android:id="@+id/tv_expense_money"
- 19 android:layout_width="wrap_content"
- 20 android:layout_height="wrap_content"
- 21 android:text="10.0000"/>
3、主逻辑OneFragment.java
- 1 List<Map<String, Object>> listitem = new ArrayList<Map<String, Object>>(); //存储数据的数组列表
- 2 //写死的数据,用于测试
- 3 int[] image_expense = new int[]{R.mipmap.detail_income, R.mipmap.detail_payout }; //存储图片
- 4 String[] expense_category = new String[] {"发工资", "买衣服"};
- 5 String[] expense_money = new String[] {"30000.00", "1500.00"};
- 6 for (int i = 0; i < image_expense.length; i++)
- 7 {
- 8 Map<String, Object> map = new HashMap<String, Object>();
- 9 map.put("image_expense", image_expense[i]);
- 10 map.put("expense_category", expense_category[i]);
- 11 map.put("expense_money", expense_money[i]);
- 12 listitem.add(map);
- 13 }
- 14
- 15 //创建适配器
- 16 // 第一个参数是上下文对象
- 17 // 第二个是listitem
- 18 // 第三个是指定每个列表项的布局文件
- 19 // 第四个是指定Map对象中定义的两个键(这里通过字符串数组来指定)
- 20 // 第五个是用于指定在布局文件中定义的id(也是用数组来指定)
- 21 SimpleAdapter adapter = new SimpleAdapter(getActivity()
- 22 , listitem
- 23 , R.layout.fragment_one_item
- 24 , new String[]{"expense_category", "expense_money", "image_expense"}
- 25 , new int[]{R.id.tv_expense_category, R.id.tv_expense_money, R.id.image_expense});
- 26
- 27 ListView listView = (ListView) v.findViewById(R.id.lv_expense);
- 28 listView.setAdapter(adapter);
以上就是整个功能实现的逻辑,本文代码中,List中呈现的数据是写死的,从数据库中获取源数据的方式可以参考我的源代码,且使用的数据库是SQLite。
源代码:https://github.com/AnneHan/ListViewDemo
SQLite数据库的使用:Android Studio 通过一个登录功能介绍SQLite数据库的使用