Reputation: 49
So im trying to make a simple image button:
<ImageButton
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_image"
android:contentDescription="@string/desc/>
xml:
public class MainActivity extends ActionBarActivity {
protected void onCreate1 (Bundle savedInstaceState){
Bundle savedInstanceState;
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById (R.id.button1);
View.setOnClickListener(new onClickListener () {
public void onClick (View v) {
Toast.makeText(v.getContext(), "You clicked it. Genius.", Toast.LENGTH_SHORT).show();
}
});
but it keeps popping up the error: "The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new onClickListener(){})"
I imported android.view.View.OnClickLIstener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.view.View.OnClickListener;
Upvotes: 1
Views: 89
Reputation:
First thing to know is that an onclick
handler implements the interface View.OnClickListener
. You need to create a class that implements the interface because you need to add your code that get’s executed. .
your onClickListener
should be be used as follows:
Button button1 = (Button) findViewById (R.id.button1);
View.setOnClickListener(new onClickListener () {
public void onClick (View v) {
Toast.makeText(v.getContext(), "You clicked it. Genius.", Toast.LENGTH_SHORT).show();
}
});
OR
By creating class Inline as follows:
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
//Inform the user the button has been clicked
}
});
Upvotes: 0
Reputation: 6107
to use onClickListener use this code
Button bTutorial1 = (Button) findViewById(R.id.tutorial1);
bTutorial1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Upvotes: 1
Reputation: 1589
you should do this:
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Use button1 and check OnClickListener casing.
Upvotes: 2