一、 重點
如何在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;<br />import android.view.MotionEvent;<br />import android.webkit.WebView;<br />import android.content.Context;<br />import android.util.AttributeSet;<br />import android.util.Log;<br />public class MyWebView extends WebView {<br /> public MyWebView(Context context) {<br /> this(context, null);<br /> }<br /> public MyWebView(Context context, AttributeSet attrs){<br /> this(context, attrs, 0);<br /> }<br /> public MyWebView(Context context, AttributeSet attrs,int defStyle) {<br /> super(context, attrs, defStyle);<br /> } // 注意實現帶三個參數的建構函式<br /> public boolean onTouchEvent(MotionEvent ev) { // 加入新功能<br /> int action = ev.getAction();<br /> Log.d("XY_TEST", "now recv key: " + action);<br /> return super.onTouchEvent(ev);<br /> }<br />}
3) 修改xml檔案
a) eclipse左側:test_xy->res->layout->main.xml修改其中內容如下
<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android=http://schemas.android.com/apk/res/android<br /> android:orientation="vertical" android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"><br /> <TextView android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="@string/hello" /><br /> <com.android.test.MyWebView<br /> android:id="@+id/myview" android:layout_height="fill_parent"<br /> android:layout_width="fill_parent" /><br /></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資訊