Android 原始碼徹底研究系列 - 鬧鐘程式, Gallery & Adapter (3)

【ysl的程式设计天堂的blog一直有看,作者的深厚技术功底与娓娓道来的清楚表达给我留下了深刻印象,苦于此blog在国内无法访问,特地将一系列经典内容转贴过来,以供学习】

本文转自: http://ysl-paradise.blogspot.com/2009/08/android-gallery-adapter-3.html

 

Android Source Code Internals - Alarm Clock, Gallery & Adapter (3)

在 AlarmClock 這個程式中,點一下主畫面上的時鐘,他會在下面列出一些鐘面圖樣,讓使用者更換時鐘的鐘面。上圖,就是這個選擇鐘面功能的執行畫面。水平拖移底下的鐘面清單,你可以看到上面的時鐘也會跟著換成新的鐘面。

這次我們就花點時間來研究看看,這樣的功能是如何實現出來的。

要追蹤這樣的功能是如何實現的,還是得先從主畫面的 layout 設計檔著手。打開 res/layout/alarm_clock.xml 檔案,你可以發現主畫面的時鐘應該是放在 clock_layout 這個 LinearLayout 中。

因此接著,我們打開主畫面的 Activity 檔 AlarmClock.java ,尋找 clock_layout 這個關鍵字。果然在 #234~#241 中,發現如下的程式片段:

mClockLayout = (ViewGroup) findViewById(R.id.clock_layout); mClockLayout.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final Intent intent = new Intent(AlarmClock.this, ClockPicker.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } });

 

mClockLayout = (ViewGroup) findViewById(R.id.clock_layout); mClockLayout.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final Intent intent = new Intent(AlarmClock.this, ClockPicker.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } });

 

原來,這個選擇鐘面的功能,是由 ClockPicker 這個 Activity 所負責實現的。

接著,在 ClockPicker 的 onCreate() 函式中,我們可以知道這個 Activity 所使用的畫面設計檔就是 res/layout/clockpicker.xml 。

同樣地,只要觀察這個 clockpicker.xml layout 設計檔,你可以發現原來選擇鐘面畫面下的鐘面清單,就是由 Gallery 這個元件所實現出來的。

<Gallery android:id="@+id/gallery" android:background="#70000000" android:layout_width="fill_parent" android:layout_height="80dip" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center_vertical" android:spacing="16dp" />

 

<Gallery android:id="@+id/gallery" android:background="#70000000" android:layout_width="fill_parent" android:layout_height="80dip" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center_vertical" android:spacing="16dp" />

 

原來,Galley 不僅僅用來顯示圖片,他也可以用來當成類似 horizontal ListView ,當成一種選單元件的功能。

先查看一下 Gallery 的繼承樹,原來他也是從 AdapterView 繼承下來。因此要對 Gallery 客製化,方法應該和 ListView 相同。

在 Android 中,所有的 AdapterView 子類,都允許你透過繼承 BaseAdpater 的方式,塞一個自己客製化過的 Adapter 給 AdapterView。

要如何寫一個自己的 Adapter?有興趣繼續研究的你,建議你打開這個不到 120 行的程式,ClockPicker.java ,好好讀一下。

你可能感兴趣的:(Android 原始碼徹底研究系列 - 鬧鐘程式, Gallery & Adapter (3))