在 SDK1.6 之后,Android就支持在XML文件中直接设置View点击时间的监听,这样又能少写一些代码咯,还能统一管理点击事件!!
下面是Android文档的说明:
XML Attributes
android:onClickName of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specifyandroid:onClick="sayHello"
, you must declare a public void sayHello(View v)
method of your context (typically, your Activity).
Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
This may also be a reference to a resource (in the form"@[package:]type:name
") ortheme attribute (in the form"?[package:][type:]name
")containing a value of this type.
This corresponds to the global attribute resource symbolonClick.
看下具体的实现:
1.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"
/>
<Button
android:text="ButtonTest"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="myClickListener"
/>
</LinearLayout>
2. MyOnClickListener.java文件
package com.ray.test; import android.app.Activity; import android.os.Bundle; import android.view.View; public class MyOnClickListener extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void myClickListener(View target){ switch (target.getId()) { case R.id.ButtonTest: setTitle("ButtonTest"); break; } } }