tags:

views:

407

answers:

2

I am a java neophyte. I followed the tutorial at http://developer.android.com/resources/tutorials/views/hello-formstuff.html to add a button and OnClick handler by copying the tutorial code into mine:

public class FormStuff extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final ImageButton button = (ImageButton) findViewById(R.id.android_button);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
                Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
            }
        });
        }
}

In Eclipse this produces two errors

Description Resource Path Location Type
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){})  FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem
The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int) FormStuff.java /FormStuffExample/src/com/example/formstuffexample line 17 Java Problem

What am I doing wrong? Thanks!

+2  A: 

Based purely on the error messages...

You're using the (implicitly) the wrong OnClickListener interface/class. It looks like there are two, View.OnClickListener and DialogInterface.OnClickListener.

The solution is to fully qualify your annonymous OnClickListener.

button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
                Toast.makeText(FormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
            }
        });
Kevin Montrose
+1One of the drawbacks of letting Eclipse resolve/fix your imports (and you being casual about it) :)
Samuh
A: 

Thanks Kevin. Followed your suggestion I fixed my error too. Eclipse offers too many hints and a newbie like me have no idea what should I choose. Later, I found another solution. If Eclipse cannot import the required when you hit O, you should manual add it:

import android.view.View.OnClickListener;
TopViet