日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android中自定义View的研究 -- 在XML中引用自定义View

發布時間:2025/6/15 Android 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android中自定义View的研究 -- 在XML中引用自定义View 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果在一直使用SetContentView(new HellwView(this)覺得總是少了一點東西,少了什么了,失去了Android中使用XML定義組件的便攜性,這種感覺讓人很不爽,呵呵,在這節里我們會看到一個自定義View報錯的解決方法,讓我們來看看在XML中定義View
  • XML中定義View的一個小錯誤

我們試著直接將錯誤的那個例子寫出來 將上一講的View例子拿出來,修改main布局:
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>
修改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中添加以下方法就解決了:
1 2 3 4 5 6 7 8 9 10 ??/** ??? ?????* 這個是我們要在XML中初始化用的 ??? ?????* */ ??? ????public HelloView(Context context,AttributeSet attrs){ ??? ???????super(context, attrs); }
運行:
關于這個解決方法網上有類似的問題:為什么非得加上這個方法,其實這個方法是作為系統解析XML中定義的屬性時作為回調方法用的。
  • 另一中在XML中引用自定義View的方法

我們也可以使用如下的方法在 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>
運行結果與上面一樣


總結

以上是生活随笔為你收集整理的Android中自定义View的研究 -- 在XML中引用自定义View的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。