Android Studio列表用法之一:ListView圖文列表顯示(實例)

前言:html

        ListView這個列表控件在Android中是最經常使用的控件之一,幾乎在全部的應用程序中都會使用到它。java

        目前正在作的一個記帳本APP中就用到了它,主要是用它來呈現收支明細,是一個圖文列表的呈現方式,下面就講講具體是如何實現的。android

 

效果圖:git

        該功能是在另外一篇博文【Android Studio 使用ViewPager + Fragment實現滑動菜單Tab效果 --簡易版】的基礎上進行添加的github

        

 

實現的思路:數據庫

        一、該功能是用fragment來作佈局的,首先建立一個fragment.xml佈局文件,在裏面添加一個ListView控件;數組

        二、因爲List裏面既要呈現圖片,也要呈現文字,因此再建立一個fragment_item.xml佈局文件,在裏面添加ImageView、TextView,用來顯示圖片和文字;佈局

        三、使用SimpleAdapter來綁定數據;測試

 

具體實現邏輯:spa

        一、建立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>

 

        二、建立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"/>

 

        三、主邏輯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數據庫的使用

相關文章
相關標籤/搜索