user2034617
user2034617

Reputation: 11

ImageButton click does not work

I tried two different ways to set up the event for an ImageButton but neither has worked. First I tried by adding onClick in the axml file:

<ImageButton
    android:src="@drawable/homeInfoButtonImages"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/homeInfoButton"
    android:layout_marginLeft="200dp"
    android:layout_marginTop="600dp"
    android:background="@null"
    android:onClick="infoButtonClick" />

In the Activity.cs:

    private void infoButtonClick()
    {
        Console.Write("Clicked");
    }

The app crashes as soon the button is clicked.

The second method I tried in Activity.cs:

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Home);

        // Create your application here
        ImageButton button = FindViewById<ImageButton>(Resource.Id.homeInfoButton);

        button.Click += delegate
        {
            infoButtonClick();
        };
    }

    private void infoButtonClick()
    {
        Console.Write("Clicked");
    }

Nothing happens when the button is clicked...

What could be causing this issue?

Upvotes: 1

Views: 2334

Answers (4)

SKall
SKall

Reputation: 5234

Console.WriteLine might have some unexpected behaviour (at least what I have experienced). The below code works fine for me.

        FindViewById<ImageButton> (Resource.Id.imageButton1).Click += (s, e) =>
            Log.Info (s.ToString (), "Image button clicked!");

Upvotes: 0

adhithiyan
adhithiyan

Reputation: 168

I code using java in eclipse.I had the same problem. So I dont know whether it will work for you.

try public void infoButtonClick() instead of private.

This solution worked for me. Thought it might help.

Upvotes: 0

Julio_oa
Julio_oa

Reputation: 580

In the method that is called from the onClick attribute on the xml, you must pass an argument of the view, and it must be public:

public void infoButtonClick(View v)
{
  Console.Write("Clicked");
}

As you can read here

Upvotes: 2

user1968030
user1968030

Reputation:

Please remove Console.Write("Clicked"); and test.

Upvotes: 1

Related Questions