【问题标题】:Xamarin.android How to get control nameXamarin.android 如何获取控件名称
【发布时间】:2017-09-07 23:29:13
【问题描述】:

我在主 Activity 的布局中添加了一个控件 (TextView)。我要原版的

<?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>

然后在代码中我得到这样的控件:

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

如何获取控件的名称(TextViewCurrentLenguajeLabel)?

我需要将其发送到翻译功能

我知道那是名称,但我需要将名称发送给方法。我想避免做这样的事情

myControl.Text = localizationMethod(“TextViewCurrentLenguajeLabel”);

我想做这样的事情

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

【问题讨论】:

  • 这是 TextView 的名称 - 你的意思是如何获取 TextView 的文本?
  • 我知道那是名称,但我需要将名称发送到我想避免做这样的事情myControl.tText = localizationMethod(“TextViewCurrentLenguajeLabel”);我想做这样的事情myControl.tText = localizationMethod(myControl.GetControlName());跨度>
  • 我明白你的意思,或者,至少我认为我明白了。我会在下面尝试回答。

标签: c# xamarin.android


【解决方案1】:

方法Android.Content.Res.Resources.GetResourceName 可以帮助您做到这一点。您可以定义以下扩展方法

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;
    }
}

并像这样使用它

var controlName = myControl.GetControlName();

【讨论】:

    【解决方案2】:

    为此,请尝试以下操作:

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

    然后使用它,通过普通的方式获取TextView

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

    然后调用localizationMethod(myControl);

    这将授予 localizationMethod 对控件的访问权限,然后您可以根据需要在方法中使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-29
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      相关资源
      最近更新 更多