33

.NET Developer here just getting started with Eclipse and Android.

Can someone show me in the simplest way possible, with the absolute fewest lines of code, how to DO something when a button is clicked?

My button has id button1 and I just want to see where/how to write the onClick() handler.

So let's say I have imageview1 set to invisible. How would I make it visible when the button is clicked?

EDIT:

Thanks everyone, but since not a single one of your examples work for me, I'll try this: Can someone please post the ENTIRE code to make this work? Not just the method, because when I try to use ANY of your methods I get errors all over the place so obviously something else is missing. I need to see everything, beginning with all the imports.

2
  • 1
    Obviously, you'll have to tell us what errors you get "all over the place"... Commented May 3, 2011 at 13:59
  • Consider using Android Studio instead of Eclipse. Commented Mar 17, 2016 at 20:46

7 Answers 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>
Sign up to request clarification or add additional context in comments.

3 Comments

See what I mean? NOTHING works LOL. "The method onClick(View) of type new View.OnClickListener(){} must override a superclass method" what is the reason for this error since I copied your text exactly?
Then take the @Override out. (Did to previous!)
Whew, this is like going back to assembly language coming from .NET. Thanks.
28

The absolutely best way: Just let your activity implement View.OnClickListener, and write your onClick method like this:

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

Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick:

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

That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.

3 Comments

I personally find this very ugly: 1) Lint will not warn you if you rename the method, you will learn about it only at runtime. 2) The method must be public in order for this to work. 3) The method must be in the activity, it will annoy you if you use fragments.
@pcans It depends what you're using it for. For example I found this use case to be very handy since I have a grid of 36 buttons to push and this is way less "ugly" than doing it the other way. If you're not using the buttons for the cases you mentioned this is a great neat way of doing things.
Yea, I would probably do it as onButton1Click(), onButton2Click(), ... It's a bit cleaner, and still keeps everything left aligned in the code base. (Less pyramid code)
7

Just declare a method,e.g:if ur button id is button1 then,

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

If you want to make the imageview1 visible then in that method write:

imageview1.setVisibility(ImageView.VISIBLE);

1 Comment

Replacing "Context" with "getApplicationContext()" worked for me: Toast.makeText(getApplicationContext(), "You mashed the button, dude.", Toast.LENGTH_SHORT).show();
5

All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.

An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.

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());
   }
}

Comments

4

Taken from: http://developer.android.com/guide/topics/ui/ui-events.html

// 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);
    ...
}

Comments

0

You can just do it in your Activity's onCreate() method. For example:

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

Comments

0

Change your onCreate to

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

for me this update worked

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.