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

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

2010-06-20 21:09 519 查看
 

 

 

一、  重点

如何在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内容如下:

package com.android.test;
import android.view.MotionEvent;
import android.webkit.WebView;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
public class MyWebView extends WebView {
public MyWebView(Context context) {
this(context, null);
}
public MyWebView(Context context, AttributeSet attrs){
this(context, attrs, 0);
}
public MyWebView(Context context, AttributeSet attrs,int defStyle) {
super(context, attrs, defStyle);
}        // 注意实现带三个参数的构造函数
public boolean onTouchEvent(MotionEvent ev) {          // 加入新功能
int action = ev.getAction();
Log.d("XY_TEST", "now recv key: " + action);
return super.onTouchEvent(ev);
}
}
 

3)         修改xml文件

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

<?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.android.test.MyWebView
android:id="@+id/myview" android:layout_height="fill_parent"
android:layout_width="fill_parent" />
</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信息

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息