您的位置:首页 > 移动开发 > Android开发

android自定义控件的创建和使用

2011-05-22 19:05 441 查看
一、 重点

如何在layout(xml)中使用自定义的控件

二、 举例

1. 功能:实现一个新的浏览器控件,使点击浏览器中任何位置都能打印Log信息

2. 步骤:

1) 建立project

a) 在eclipse中点击菜单File->New->Project……

b) 选择Android Project按Next

c) 填写project的各项内容如下

Project name: test_xy // 目录名, 它位于你设定的workspace之下

Package name: com.android.test //打包名称

Activity name: .TestXy // 类名(生成文件TestXy.java)

Application name: test_xy // 可执行程序名

然后点Finish按钮

2) 继承一个已有控件,加入新的属性和方法

a) eclipse左侧:test_xy->src->com.android.test 点右键 New->class

b) 建立新控件:Name: MyWebView,其它使用默认选项

MyWebView.java内容如下:

view plaincopy to clipboardprint?
01.package com.android.test;
02.import android.view.MotionEvent;
03.import android.webkit.WebView;
04.import android.content.Context;
05.import android.util.AttributeSet;
06.import android.util.Log;
07.public class MyWebView extends WebView {
08. public MyWebView(Context context) {
09. this(context, null);
10. }
11. public MyWebView(Context context, AttributeSet attrs){
12. this(context, attrs, 0);
13. }
14. public MyWebView(Context context, AttributeSet attrs,int defStyle) {
15. super(context, attrs, defStyle);
16. } // 注意实现带三个参数的构造函数
17. public boolean onTouchEvent(MotionEvent ev) { // 加入新功能
18. int action = ev.getAction();
19. Log.d("XY_TEST", "now recv key: " + action);
20. return super.onTouchEvent(ev);
21. }
22.}

3) 修改xml文件

a) eclipse左侧:test_xy->res->layout->main.xml修改其中内容如下

view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
03. android:orientation="vertical" android:layout_width="fill_parent"
04. android:layout_height="fill_parent">
05. <TextView android:layout_width="fill_parent"
06. android:layout_height="wrap_content"
07. android:text="@string/hello" />
08. <com.android.test.MyWebView
09. android:id="@+id/myview" android:layout_height="fill_parent"
10. android:layout_width="fill_parent" />
11.</LinearLayout>

注意使用全名, 即com.android.test.MyWebView, 否则找不到新控件

4) 运行

a) 在eclipse中点击菜单Run->Run Configurations……

b) 双击左边的Android Application,产生了一个New Configuration,点开它填写内容如下:

Name: yan_config // 随便起一个

Project: test_xy // 刚才起的project, 即目录名

c) 点击Apply,然后点Run,多等一会儿就出来了

d) 此时点击右上的DDMS,可看到Log信息,在触摸WebView控件时,可看到刚才加入的Log信息

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/super005/archive/2010/06/20/5682229.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: