Android onClick事件三种实现方法

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class HelloActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btnMethod01;
        Button btnMethod02;
        Button btnMethod03;
        
        btnMethod01 = (Button)findViewById(R.id.button1);
        btnMethod02 = (Button)findViewById(R.id.button2);
        btnMethod03 = (Button)findViewById(R.id.button3);
        
        //第一种方法:匿名类
        btnMethod01.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View v){
                Toast.makeText(HelloActivity.this,R.string.method01
                        ,Toast.LENGTH_SHORT).show();
            }
            
        });
        
        //添加监听事件
        btnMethod02.setOnClickListener(new button1OnClickListener());
    }
    //第二种方法:内部类实现  有两部 1.写内部类 2.添加监听事件
    private class button1OnClickListener implements OnClickListener{
        public void onClick(View v){
            Toast.makeText(HelloActivity.this,R.string.method02,
                    Toast.LENGTH_SHORT).show();
        }
        
    }
    //第三种方法:用xml方法配置,该名称要与  main.xml 中button03的 
    //android:onClick="OnClickButton03"的名字一样
    public void OnClickButton03(View v){
        Toast.makeText(HelloActivity.this,R.string.method03
                ,Toast.LENGTH_SHORT).show();
    }
    
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/method01"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/method02"/>

    <Button
        android:onClick="OnClickButton03"
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/method03"/>

</LinearLayout>
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值