【學習筆記】Android自訂控制項

來源:互聯網
上載者:User

標籤:自訂控制項

本文是在學習郭霖大神的《第一行代碼-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自訂控制項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.