編輯:關於 Android 程式設計
ListView 是 Android 裡最常被用到的控件之一,而它裡面的每一個子項(Item)既可以只是一串文字,也可以是一個由多個控件組成的複合版面。本文先從最基礎的 ListView 講起。
實現 ListView 大致分四步:
1. 準備好要顯示的資料;
2. 用一維或多維動態陣列把資料裝起來;
3. 建立 Adapter——你可以把它理解為 Item 的工廠,動態陣列裡有多少筆資料,就產生多少個 Item;
4. 把 Adapter 交給 ListView,顯示出來。
先看本文程式碼實現的效果:
main.xml 很簡單:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="https://schemas.android.com/apk/res/android"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/MyListView"> </ListView> </LinearLayout>
my_listitem.xml 用於設計 ListView 的 Item:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:layout_width="fill_parent" xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_height="wrap_content" android:id="@+id/MyListItem" android:paddingBottom="3dip" android:paddingLeft="10dip"> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/ItemTitle" android:textSize="30dip"> </TextView> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/ItemText"> </TextView> </LinearLayout>
這裡用到的幾個屬性值得說明:
1. paddingBottom="3dip"——Layout 底部留出 3 個像素的空白;
2. paddingLeft="10dip"——Layout 左側留出 10 個像素的空白;
3. textSize="30dip"——TextView 的字級設為 30。
最後是 Java 程式碼:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //綁定XML中的ListView,作為Item的容器 ListView list = (ListView) findViewById(R.id.MyListView); //生成動態數組,並且轉載數據 ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); for(int i=0;i<30;i++) { HashMap<String, String> map = new HashMap<String, String>(); map.put("ItemTitle", "This is Title....."); map.put("ItemText", "This is text....."); mylist.add(map); } //生成適配器,數組===》ListItem SimpleAdapter mSchedule = new SimpleAdapter(this, //上下文 mylist,//數據來源 R.layout.my_listitem,//ListItem的XML實現 //動態數組與ListItem對應的子項 new String[] {"ItemTitle", "ItemText"}, //ListItem的XML文件裡面的兩個TextView ID new int[] {R.id.ItemTitle,R.id.ItemText}); //添加並且顯示 list.setAdapter(mSchedule); }
關鍵是 SimpleAdapter 那兩個陣列的對應關係:String[] 裡是資料來源 HashMap 的 key 名稱,int[] 裡是 Item 佈局中要填入的控件 id,兩者按位置一一對應。搞懂這層映射,最簡單的列表就完成了。
Android 小遊戲 2048 重構筆記:自定義方塊、手勢操作與存檔設計
2048 是一個規則簡單、容易上手的小遊戲,但若要在 Android 上做出流暢且可維護的版本,仍需要仔細安排方塊、手勢、分數與存檔邏輯。本文以重構後的版本為例,整理其設
用反射呼叫系統隱藏遠程服務,實作來電攔截
早期版本的 Android 在 TelephonyManager 上開放了一個 endCall() 方法,掛斷來電一行程式碼就能搞定。但 Google 後來意識到,對一支
源碼分享:Android 即時通訊與 SNS 開源專案精選
本文整理了一批適合 Android 開發者參考與二次開發的即時通訊與社交類開源專案,內容涵蓋聊天、朋友圈、位置社交、興趣社群、團隊協作等多種常見場景。部分專案已開源於 G
Android 性能優化:ListView 的 ViewHolder 重用機制
相信大家在開發中都大量使用過 ListView,但你有沒有遇到過這樣的困擾:當數據量特別大時,向下滑動列表會出現明顯的卡頓?這就需要我們對它進行優化。 ListView