標籤:des android style class blog code
--by San[[email protected]]
在編寫列表時,如果是普通的列表,使用ListView + ArrayAdapter 即可實現,但是如果要在每個清單項目中文字前配一個表徵圖了,或者在文字後面再配一個表徵圖,這個就可以用 SimpleAdapter 實現了,不要被它的名字欺騙了,It is not simple, it is powerful.
我們以製作一個帶表徵圖的菜單列表為例,首先我們建立一個布局檔案 menu_frame.xml,裡麵包含一個 ListView, 代碼如下:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:padding="5dp" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <ListView 8 android:id="@+id/menu_list" 9 android:layout_width="match_parent"10 android:layout_height="wrap_content"11 />12 13 </LinearLayout>
然後我們建立一個功能表項目的布局檔案 menu_items.xml, 裡麵包含一個 ImageView 和一個 TextView, 代碼如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:id="@+id/menu_item" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="horizontal" 7 android:paddingTop="40dp"> 8 9 <!-- 功能表項目的表徵圖 -->10 <ImageView11 android:id="@+id/menu_img"12 android:layout_width="wrap_content"13 android:layout_height="wrap_content"14 android:paddingLeft="10dp"15 android:contentDescription="@string/hello_world"16 />17 18 <!-- 功能表項目的文字 -->19 <TextView20 android:id="@+id/menu_name"21 android:layout_width="wrap_content"22 android:layout_height="wrap_content"23 android:paddingLeft="10dp"24 android:textSize="20sp"25 />26 27 </LinearLayout>
菜單和功能表項目的布局都編寫好了,現在把他們結合起來
1 String[] menuNames = {"first", "second", "third", "fouth" }; 2 int[] menuImg = { 3 R.drawable.ic_top_bar_send_disabled, 4 R.drawable.ic_about_us, 5 R.drawable.ic_app_recommendation, 6 R.drawable.ic_article_more_item_read_it_later 7 }; 8 List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); 9 for (int i = 0; i < menuNames.length; i++ ) {10 Map<String, Object> listItem = new HashMap<String, Object>();11 listItem.put("img", menuImg[i]);12 listItem.put("name", menuNames[i]);13 listItems.add(listItem);14 }15 SimpleAdapter sampleAdapter = new SimpleAdapter(this16 , listItems17 , R.layout.menu_items18 , new String[] {"img", "name"}19 , new int[] { R.id.menu_img, R.id.menu_name}20 );21 22 menuListView = (ListView)findViewById(R.id.menu_list);23 menuListView.setAdapter(sampleAdapter);
這裡面主要就是 SimpleAdapter, 說一下幾個參數的意思
- 第二個參數是一個 List<Map<String, ?>> 的集合,該集合中每個 Map<String, ?> 可產生一本清單項目
- 指定一個布局介面的 ID
- 該參數是一個 String[] 類型的參數,該參數決定取 Map<String, ?> 對象中哪些 key 對應的 value 來產生清單項目
- 該參數是一個 int[] 類型的參數,該參數決定填充哪些組建(對應 menu_items.xml 中定義的id)