Android之Button按钮点击事件的三种方法

通过三种方法实现Button的点击事件,通过泛型简化查找控件的id。

package com.carlos.button;

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

public class MainActivity extends Activity {

    private Button button1;
    private Button button2;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = getViewById(R.id.button1);
        button2 = getViewById(R.id.button2);

        // 第一种方法,匿名内部类实现点击事件。
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                showInfo(1);
            }
        });

        // 第二种方法,调用外部定义的点击事件接口实现。
        button2.setOnClickListener(listener);
    }

    // 定义接口给button2使用
    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            showInfo(2);
        }
    };

    // 第三种方法,xml布局里面定义button3的onClick事件
    public void button(View v) {
        showInfo(3);
    };

    // 用Logcat显示日志观察点击的哪一项
    void showInfo(int i) {
        Log.i(TAG, "你点击了第" + i + "个按钮");
    }

    // 通过泛型简化findViewById
    @SuppressWarnings("unchecked")
    <T extends View> T getViewById(int id) {
        try {
            return (T) findViewById(id);
        } catch (ClassCastException e) {
            Log.e(TAG, "Could not cast View to create class.", e);
            throw e;
        }
    }

}

xml布局

<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="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="button"
        android:text="Button3" />

</LinearLayout>

Logcat日志中TAG标签的结果
Logcat日志中TAG标签的结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值