如果在一直使用 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 > 运行结果与上面一样





更多相关文章

  1. 【自定义控件】android事件分发机制
  2. 在这白驹过隙的时代,Android开发者如何先人一步?
  3. Android保持屏幕常亮的两种方法
  4. 自定义Android(安卓)TextView超链接处理
  5. Android(安卓)异步调用,AsyncTask的简单用法
  6. Android进阶(一)-------Android中AsyncTask的简单用法
  7. android 事件机制与事件监听(一)
  8. Android(安卓)studio升级gradle4.x后自定义打包文件名
  9. Android(安卓)sdk content loader 0%的解决方案

随机推荐

  1. Android(安卓)xml资源文件中@、@android:
  2. [Google Android] Android(安卓)SDK Tool
  3. 【转】Android(安卓)ADB命令集
  4. Android(安卓)studio使用笔记。。。
  5. Android学习路线图
  6. android 各种小项目
  7. Android: Android图形基础
  8. Android(安卓)API中文文档AccessibilityS
  9. android:ellipsize的使用
  10. android布局属性