Android自訂View研究(四) — 在XML中定義View

來源:互聯網
上載者:User

如果在一直使用SetContentView(new HellwView(this)感覺總是少了一點東西,少了什麼了,失去了Android中使用XML定義組件的方便性性,這種感覺讓人很不爽,呵呵,在這節裡我們會看到一個自訂View報錯的解決方案,讓我們來看看在XML中定義View吧

 

一、在XML中定義View的一個小錯誤

 

我們試著直接將錯誤的那個例子寫出來

將上一講的View例子拿出來,修改main布局:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

    <com.fxhy.stady.HelloView

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    />

</LinearLayout>

 

 

修改MainActivity

super.onCreate(savedInstanceState);

         setContentView(R.layout.main);// 使用自訂的View

運行:

                                       

                                  

 

 

       我們發現,竟然報錯了,我們在LogCat裡查看下:

 

11-24 10:58:38.993: ERROR/AndroidRuntime(323): Caused by: java.lang.NoSuchMethodException: HelloView(Context,AttributeSet)

 

竟然是沒有HelloView(Context,AttributeSet)這個構造器,結局方法呼之欲出了,呵呵。

 

二、解決方案

只需要在HelloView 中添加以下方法就解決了:

    /**

     * 這個是我們要在XML中初始化用的

     * */

    public HelloView(Context context,AttributeSet attrs){

       super(context, attrs);

}

 

運行:

 

       

 

關於這個解決方案網上有類似的問題:為什麼非得加上這個方法,其實這個方法是作為系統解析XML中定義的屬性時作為回調方法用的。如果想更深入的瞭解View以及剛才的解決方案的原理的話,可以關注我的部落格,我會在以後的《深入解析View原理》中講解,呵呵,說不定有時候會有一種豁然開朗的感覺。

 

三、另一中在XML中的View布局

我們也可以使用如下的方法在XML中添加View

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="@string/hello"

    />

    <view class="com.fxhy.stady.HelloView"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    />

</LinearLayout>

運行結果與上面一樣

 

             

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.