hameed hameed - 1 month ago 13
Android Question

How to use One imageview variable that refer to multiple imagesViews in Xamarin

Im trying to create a simple Connect 3 game in Xamarin it has 9 ImageView, I created this Connect 3 in Android Studio using Java. In Android Studio i can import View.view at the begining and use that view to ImageView and refer to any imageView within the application without using FindingViewById Function. Like this.

public void dropIn(View view){
count= 0;
ImageView image = (ImageView)view; // You dont have to use FindViewby ID this referes to every imageView which is used.
if (count == 0) {
image.SetImageResource(Resource.Drawable.yellow);
count = 1;
}
else
{
image.SetImageResource(Resource.Drawable.red);
count = 0;
}


My Queston: Is there any to implement the same thing in Xamarin

count=0
ImageView image = FindViewById<ImageView>(Resource.Id.imageView1) //there are 9 Images like imageView2,imageView3 and etc till imageView9
image.Click += delegate
{
if (count == 0) {
image.SetImageResource(Resource.Drawable.yellow);
count = 1;
}
else
{
image.SetImageResource(Resource.Drawable.red);
count = 0;
}

Answer

If I understand you correctly, you want the same Click Event handler for all your ImageView's.

The EventArgs for the Event fired on Clicked, does contain the sender, which would be the ImageView responsible for the click:

void ImageClicked(object sender, EventArgs args)
{
    var image = (ImageView)sender;
    // do stuff to the image...
}

Then just hook it up to your images:

image1.Click += ImageClicked;
image2.Click += ImageClicked;

Or you could export a similar dropIn method:

[Export("dropIn")]
public void DropIn(View view)
{
    var image = (ImageView)view;
    // do stuff
}

You need to make sure to Export it so Android can find it from the native side.

Then you can use it in your XML/AXML as usual:

<ImageView
    android:onClick="dropIn"

To get this to work properly you probably need to add a reference to Mono.Android.Export