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

本文转自:http://lovewf.blog.51cto.com/1723922/724124

  如果在一直使用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>
复制代码

运行结果与上面一样

 

个人发现:

<View class="com.fxhy.stady.HelloView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

view中的第一个字符View 大写以后,会显示空白页面,但是无警报!

posted @   似水流云  阅读(204)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示