foluis
foluis

Reputation: 1038

Xamarin.android How to get control name

I have added a control (TextView) to a layout in the main Activity. I want to get the original

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:text="@string/currentLenguajeLabel"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/TextViewCurrentLenguajeLabel" />
</LinearLayout>

Then in the code I get the control like this:

TextView myControl = FindViewById<TextView>(Resource.Id.TextViewCurrentLenguajeLabel);

How can I get the name of the control (TextViewCurrentLenguajeLabel)?

I need it to send it to a translation function

I know that that is the name, but I need to send the name to a method. I want to avoid to do something like this

myControl.Text = localizationMethod(“TextViewCurrentLenguajeLabel”);

I want to do something like this

myControl.Text = localizationMethod(myControl.GetControlName());

Upvotes: 1

Views: 1695

Answers (2)

Claudio Redi
Claudio Redi

Reputation: 68400

Method Android.Content.Res.Resources.GetResourceName could help you to do this. You could define the following extension method

public static class ViewExtensions
{
    public static string GetControlName(this View view)
    {
        string controlName = "";
        if (view.Id > 0)
        {
            string fullResourceName = Application.Context.Resources.GetResourceName(view.Id)
            controlName = fullResourceName.Split('/')[1];
        }
        return controlName;
    }
}

And use it like this

var controlName = myControl.GetControlName();

Upvotes: 3

Ewald
Ewald

Reputation: 5751

To do this, try the following:

void localizationMethod(TextView tv)
{
  tv.Text = "Some New Text";
}

Then to use it, get the TextView via the normal

TextView myControl = FindViewById<TextView>(Resource.Id.TextViewCurrentLenguajeLabel);

And then calling localizationMethod(myControl);

This will give the localizationMethod access to the control and you can then work with it in the method as you wish.

Upvotes: 1

Related Questions