Android中自定义View的研究(四) -- 在XML中定义View

       若是在一直使用 SetContentView(new HellwView(this) 噶虐老是少了一点东西,少了什么了,失去了 Android 中使用 XML 定义组件的便携性,这种感受让人很不爽,呵呵,在这节里咱们会看到一个自定义 View 报错的解决方法,让咱们来看看在 XML 中定义 View
 

1、XML中定义View的一个小错误 java

 
咱们试着直接将错误的那个例子写出来
将上一讲的 View 例子拿出来,修改 main 布局:

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

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

    android:orientation="vertical" this

    android:layout_width="fill_parent" spa

    android:layout_height="fill_parent" xml

    > utf-8

<TextView  博客

    android:layout_width="fill_parent" string

    android:layout_height="wrap_content" it

    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) 这个构造器,结局方法呼之欲出了,呵呵。
 

2、解决方法

只须要在 HelloView  中添加如下方法就解决了:

    /**

     * 这个是咱们要在XML中初始化用的

     * */

    public HelloView(Context context,AttributeSet attrs){

       super(context, attrs);

}
 
运行:
 

 
关于这个解决方法网上有相似的问题:为何非得加上这个方法, 其实这个方法是做为系统解析 XML 中定义的属性时做为回调方法用的 。若是想更深刻的了解 View 以及刚才的解决方案的原理的话,能够关注个人博客,我会在之后的 《深刻解析 View 原理》 中讲解,呵呵,说不定有时候会有一种豁然开朗的感受。
 

3、另外一中在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 >
运行结果与上面同样

  
相关文章
相关标签/搜索