標籤:自訂控制項
本文是在學習郭霖大神的《第一行代碼-Android》中關於“自訂控制項”的總結。
相似的方法,如果新的方法沒有什麼特別的優勢,我還是會用舊的方法。一直以來我都不理解在布局檔案中使用包名作為一個控制項,也不知道這種方法的好處,所以我從來不用。在以前接觸的書中對自訂控制項沒有講解,在我看的網上的Demo上,我也感覺不到自訂控制項的優勢,所以一直以來我還是用系統給的控制項。我曾試圖從網上搜尋學習自訂控制項,但是沒有講解很到位的。當我看到《第一行代碼-Android》時,我做的第一件事情,就是找找有沒有關於“用包名做控制項”的介紹。我終於找到了。
自訂的布局能夠實現更複雜、更符合我們期望的功能,當然也能提高我們的編程效率。
自訂控制項是需要指定完整的類名的,所以我們先建立一個類TitleLayout繼承自LinearLayout。
public class TitleLayout(Context context, AttributeSet attrs){ public TitleLayout(Context context, AttributeSet attrs){ super(context, attrs); LayoutInflater.from(context).inflate(R.layout.title, this); }}在這個類中,我們重新了LinearLayout中的帶兩個參數的建構函式,在布局中引入TitleLayout控制項就會調用這個建構函式。
現在自訂控制項已經建立好了,現在我們需要在布局檔案中添加這個自訂控制項:
<pre name="code" class="java"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.uicustomviews.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content">
</com.example.uicustomviews.TitleLayout>
</
LinearLayout
>
【學習筆記】Android自訂控制項