如何处理一个按钮被点击Android中? [英] How to handle a button being clicked in Android?

查看:174
本文介绍了如何处理一个按钮被点击Android中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的出现似乎是处理按钮的点击3常见的方式,多少也是有差别的方法之间?而任何人在某种程度上'好'?

In Android there seems to be 3 common ways of handling button clicks, how much difference is there between the methods? And are any of them 'better' in some way?

这三种方法我一直看到的是:

The three methods I keep seeing are:

匿名类

查找按钮,通过它的ID,然后通过一个新的匿名类 setOnClickListener ,例如:在的onCreate

Find the button by it's ID, then pass a new anonymous class to setOnClickListener, e.g. in onCreate

findViewById(R.id.myButton).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // .. Whatever
    }
});

实现OnClickListener

实施 OnClickListener 并通过 setOnClickListener ,然后使用基于所述按钮的ID,例如,一个开关说明书在的onCreate

Implement OnClickListener and pass this to setOnClickListener, then use a switch statment based on the button ID, e.g. in onCreate

findViewById(R.id.myButton).setOnClickListener(this);

和实施的onClick 喜欢

public void onClick(View v) {
    switch(v.getId()) {
        case R.id.myButton:
            // ... whatever ...
            break;
    }
}

使用的onClick XML属性附加伤害

在为您的活动的XML布局,而不是给你的按钮的ID,使用的onClick 是这样的:

In the XML layout for your activity, instead of giving your button an ID, use onClick like this:

<Button 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:onClick="buttonClicked" 
    android:text="Button" />

然后有一个 buttonClicked 方法,在你的Acitiviy是这样的:

Then have a buttonClicked method in your Acitiviy like this:

public void buttonClicked(View v) {
    // ... whatever ...
}

目前,我倾向于使用XML属性,但是这只是因为它涉及最少的code。什么时候应该使用其他的方法?

At the moment I tend to use the XML attribute, but that's just because it involves the least amount of code. When should I use the other methods?

推荐答案

前两个都是经典方法。哪一个你preFER更多的是一般的Java问题不是一个Android的问题。 第三个后来加入使事情变得更容易。

The first two are the classic approaches. Which one you prefer is more of a general Java question than an Android question. The third one was added later to make things easier.

设置一个点击监听器上的按钮是非常常见的任务,但它   需要相当多的样板code。减少量的一种方式   样板是几个之间共享一个单一的点击监听器   按钮。虽然这种技术减少类的数量,它仍然   需要code相当数量的,它仍然需要为每个   按钮,在你的XML布局文件的ID。随着Android 1.6的,没有这   是必要的。所有你所要做的就是在声明一个公共的方法你   活动以处理click(该方法必须有一个查看参数)

Setting up a click listener on a button is very common task, but it requires quite a bit of boilerplate code. One way to reduce the amount of boilerplate is to share a single click listener between several buttons. While this technique reduces the number of classes, it still requires a fair amount of code and it still requires giving each button an id in your XML layout file. With Android 1.6, none of this is necessary. All you have to do is declare a public method in your Activity to handle the click (the method must have one View argument)

来源

这篇关于如何处理一个按钮被点击Android中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆