Android 在XML文件中添加View点击事件的监听:OnClickListener

在 SDK1.6 之后,Android就支持在XML文件中直接设置View点击时间的监听,这样又能少写一些代码咯,还能统一管理点击事件!!

下面是Android文档的说明:

XML Attributes

android:onClick

Name 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;
         }
       }
 }
 






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值