现在的位置: 首页 > 综合 > 正文

在Layout xml中配置自定义View

2018年07月13日 ⁄ 综合 ⁄ 共 945字 ⁄ 字号 评论关闭

1. Layout xml文件中的配置

    main.xml

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="fill_parent"  
  3.     android:layout_height="fill_parent"  
  4.     android:orientation="vertical">  
  5.     <com.larry.testbuild.MyListView android:id="@+id/my_list"  
  6.         android:layout_width="fill_parent"  
  7.         android:layout_height="fill_parent"/>  
  8. </RelativeLayout>  

注意在引用自定义的View类时,要写出类的全路径,即包名.类名


2. 自定义的View,这里以继承ListView为例

   MyListView.java

  1. package com.larry.testbuild  
  2.   
  3. public class MyListView extends ListView {  
  4.     public DishListView(Context context) {  
  5.         super(context);  
  6.     }  
  7.     public DishListView(Context context, AttributeSet attrs) {  
  8.         super(context, attrs);  
  9.     }  
  10.   
  11. ...  
  12.  }  

注意需要继承父类的两个构造函数,少一个都会造成Force close。


对于ListView这样做的好处是,不需要将Adapter的子类定义置于ListView所在的父Activity类中。增强ListView的模块化,从而降低耦合,增强复用性。

本帖转自:http://blog.csdn.net/larryl2003/article/details/6639532

抱歉!评论已关闭.