Android中自定义View的研究 -- 在XML中引用自定义View
生活随笔
收集整理的這篇文章主要介紹了
Android中自定义View的研究 -- 在XML中引用自定义View
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如果在一直使用SetContentView(new HellwView(this)覺(jué)得總是少了一點(diǎn)東西,少了什么了,失去了Android中使用XML定義組件的便攜性,這種感覺(jué)讓人很不爽,呵呵,在這節(jié)里我們會(huì)看到一個(gè)自定義View報(bào)錯(cuò)的解決方法,讓我們來(lái)看看在XML中定義View吧
修改MainActivity
我們發(fā)現(xiàn),竟然報(bào)錯(cuò)了,我們?cè)?/span>LogCat里查看下: 11-24 10:58:38.993:ERROR/AndroidRuntime(323): Caused by:java.lang.NoSuchMethodException: HelloView(Context,AttributeSet) 竟然是沒(méi)有HelloView(Context,AttributeSet)這個(gè)構(gòu)造器,結(jié)局方法呼之欲出了,呵呵。
運(yùn)行:
關(guān)于這個(gè)解決方法網(wǎng)上有類(lèi)似的問(wèn)題:為什么非得加上這個(gè)方法,其實(shí)這個(gè)方法是作為系統(tǒng)解析XML中定義的屬性時(shí)作為回調(diào)方法用的。
運(yùn)行結(jié)果與上面一樣
-
在XML中定義View的一個(gè)小錯(cuò)誤
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?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> |
super.onCreate(savedInstanceState);
? ? ? ? setContentView(R.layout.main);// 使用自定義的View 運(yùn)行:我們發(fā)現(xiàn),竟然報(bào)錯(cuò)了,我們?cè)?/span>LogCat里查看下: 11-24 10:58:38.993:ERROR/AndroidRuntime(323): Caused by:java.lang.NoSuchMethodException: HelloView(Context,AttributeSet) 竟然是沒(méi)有HelloView(Context,AttributeSet)這個(gè)構(gòu)造器,結(jié)局方法呼之欲出了,呵呵。
-
解決方法
| 1 2 3 4 5 6 7 8 9 10 | ??/** ??? ?????* 這個(gè)是我們要在XML中初始化用的 ??? ?????* */ ??? ????public HelloView(Context context,AttributeSet attrs){ ??? ???????super(context, attrs); } |
關(guān)于這個(gè)解決方法網(wǎng)上有類(lèi)似的問(wèn)題:為什么非得加上這個(gè)方法,其實(shí)這個(gè)方法是作為系統(tǒng)解析XML中定義的屬性時(shí)作為回調(diào)方法用的。
-
另一中在XML中引用自定義View的方法
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | <?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> |
總結(jié)
以上是生活随笔為你收集整理的Android中自定义View的研究 -- 在XML中引用自定义View的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android 在xml文件中引用自定义
- 下一篇: Android app按三层架构+MVC