如何捕捉按钮的点击事件?

33

我是一名.NET开发人员,刚开始接触 Eclipse 和 Android。

请问有人能以最简单的方式向我展示如何在点击按钮时执行某些操作吗?代码行数越少越好。

我的按钮ID为button1,我只想知道在哪里/如何编写onClick()处理程序。

比方说,我将imageview1设置为不可见。当按钮被点击时,我该如何使其可见?

编辑:

谢谢大家,但由于你们中没有一个例子对我起作用,我会尝试这个:有人可以发布使此工作的全部代码吗?不仅仅是方法,因为当我尝试使用任何您的方法时,我遇到了错误,所以显然还缺少其他东西。我需要看到所有内容,从所有导入开始。


1
显然,你必须告诉我们你到处遇到了哪些错误…… - Julian
考虑使用Android Studio而不是Eclipse。 - Al Lelopath
7个回答

38

/src/com/example/MyClass.java

package com.example

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

public class MyClass extends Activity
{

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    

    Button button = (Button) findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener()
    {
      public void onClick(View v)
      {
         ImageView iv = (ImageView) findViewById(R.id.imageview1);
         iv.setVisibility(View.VISIBLE);
      }
    });

  }
}

/res/layout/main.xml

<?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">
    <Button 
      android:text="Button"
      android:id="@+id/button1"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
    />
    <ImageView 
      android:src="@drawable/image" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:id="@+id/imageview1"
      android:visibility="invisible"
    />
</LinearLayout>

你明白我的意思吗?什么都不起作用,哈哈。"The method onClick(View) of type new View.OnClickListener(){} must override a superclass method" 这个错误的原因是什么,既然我已经完全复制了你的文本? - Jimmy D
然后把 @Override 去掉。(之前加上了!) - Ben Williams
12
哎呀,从.NET回到汇编语言真是让人心累。谢谢。 - Jimmy D

28

绝对最佳的方法:只需让您的活动实现View.OnClickListener,并像这样编写您的onClick方法:

public void onClick(View v) {
    final int id = v.getId();
    switch (id) {
    case R.id.button1:
        // your code for button1 here
        break;
    case R.id.button2:
        // your code for button2 here
        break;
    // even more buttons here
    }
}

然后,在你的XML布局文件中,你可以使用属性android:onClick直接设置点击监听器:

<Button
    android:id="@+id/button1"
    android:onClick="onClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1" />

这是最清晰的方法。我今天在所有我的项目中都使用它。


4
个人认为这很不美观:1)如果你重命名该方法,Lint 不会警告你,只有在运行时才会发现。2)该方法必须是公共的才能起作用。3)该方法必须在活动中,如果使用片段将会很麻烦。 - pcans
1
@pcans 这取决于你使用它的目的。例如,我发现这种用法非常方便,因为我有一个由36个按钮组成的网格需要按下,而这种方法比另一种方法要少得多丑陋。如果你不是用按钮来处理你提到的情况,那么这是一个很好的整洁的做事方式。 - Barry Michael Doyle
是的,我可能会将其编写为onButton1Click(),onButton2Click()等。这样代码更加清晰,而且仍然保持了代码库中所有内容的左对齐(减少了金字塔式代码)。 - WallMobile

7

只需声明一个方法,例如:如果您的按钮ID为button1,则:

button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(Context, "Hello", Toast.LENGTH_SHORT).show();
        }
    });

如果您想使ImageView1可见,则在该方法中编写以下内容:
imageview1.setVisibility(ImageView.VISIBLE);

1
使用“getApplicationContext()”替换“Context”对我有用: Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show(); - B. Clay Shannon-B. Crow Raven

5

所有的答案都基于匿名内部类。我们还有一种为按钮以及其他组件添加点击事件的方法。

一个活动需要实现 View.OnClickListener 接口,我们需要重写 onClick 函数。我认为这是与使用匿名类相比最好的方法。

package com.pointerunits.helloworld;

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

public class MainActivity extends Activity implements OnClickListener {
   private Button login;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      login = (Button)findViewById(R.id.loginbutton);
      login.setOnClickListener((OnClickListener) this);
      Log.i(DISPLAY_SERVICE, "Activity is created");

   }    

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {

      getMenuInflater().inflate(R.menu.main, menu);
      return true;
    }

   @Override
   public void onClick(View v) {
     Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
   }
}

更加清晰。谢谢。 - Hephaestus

4

内容来源: http://developer.android.com/guide/topics/ui/ui-events.html

UI事件是当用户与设备交互时发生的事件。这些事件包括触摸、按键和手势等操作。应用程序可以通过实现特定的回调方法来响应这些事件。
以下是一些常见的UI事件类型:
- 触摸事件:当用户触摸屏幕时,会发生这种事件。它包括了按下、移动和抬起等动作。 - 按键事件:当用户按下或释放按键时,会发生这种事件。它也可以包括长按和多个按键同时按下等操作。 - 手势事件:当用户执行某些特定的手势操作时,会发生这种事件。例如,滑动、捏合和双击等操作。
要处理UI事件,应该在代码中注册相应的监听器,然后在监听器中实现适当的回调方法。这些回调方法将自动被调用,以响应相应的事件。
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
      // do something when the button is clicked
    }
};

protected void onCreate(Bundle savedValues) {
    ...
    // Capture our button from layout
    Button button = (Button)findViewById(R.id.corky);
    // Register the onClick listener with the implementation above
    button.setOnClickListener(mCorkyListener);
    ...
}

0

将您的onCreate更改为

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

对我来说,这个更新起作用了。


0
你可以在Activity的onCreate()方法中完成它。例如:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Assign the button to a variable
    Button button1 = (Button)findViewById(R.id.button1);

    //Assign the ImageView to a final variable, so that it's
    //accessible from an inner class
    ImageView imageView = (ImageView)findViewById(R.id.imageview1);

    //Assign it a new OnClickListener
    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView.setVisibility(View.VISIBLE);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接