欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 运维知识 > android >内容正文

android

android自定义view研究(四) -凯发k8官方网

发布时间:2024/10/8 android 0 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 android自定义view研究(四) -- 在xml中定义view 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

       如果在一直使用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以及刚才的凯发k8官方网的解决方案的原理的话,可以关注我的博客,我会在以后的《深入解析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>

运行结果与上面一样

 

             

 

          

 

 

               ok源码下载

               ok源码下载2

               ok源码下载3

转载于:https://www.cnblogs.com/lovewf/archive/2011/11/28/2264473.html

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是凯发k8官方网为你收集整理的android自定义view研究(四) -- 在xml中定义view的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

网站地图