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>
运行结果与上面一样



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值