首页 > 解决方案 > 在 Xamarin.UiTest 中访问视图的自定义属性

问题描述

我有一个使用名为“组件”的 Android 类库项目创建的自定义 android 视图类,其自定义属性在 Resources/values/Attrs.xml 中定义

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <declare-styleable name="SwitchWithData">
   ...
    <attr name="isOn" format="boolean"/>
  </declare-styleable>
</resources>

自定义视图类在 CustomView.cs 中使用公共属性定义。

 public bool IsOn {
        get { return _isOn; }
        set { _isOn = value; SeIsOn(value); }
    }

在布局或代码中使用自定义视图时,我可以访问该属性。

android项目参考组件项目-resource/layout.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical">
                    ...
                    <Components.CustomView  
                     app:IsOn="true"
                     android:id="@+id/CustomView"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"/>

</LinearLayout>

即使从代码访问属性也可以正常工作。- MainActivity.cs

    customView = FindViewById<Components.CustomView>(Resource.Id.CustomView);
    customView.IsOn = true;

所以问题是从 Xamarin.UiTest 项目访问这个属性。通常我通过调用这样的调用方法来访问属性。

app.Query(x => x.Id("Switch").Invoke("isChecked").Value<bool>()).First();

这适用于 android 本机视图,但是当我尝试使用相同的方法访问我的自定义视图的属性时,它返回空对象。

app.Query(x => x.Id("CustomView").Invoke("isOn").Value<bool>()).First();

知道我在做什么错吗?

标签: xamarin.androidandroid-custom-viewxamarin.uitest

解决方案


好的,我想通了。问题出在组件类中。根据此链接,必须有一个具有命名导出属性的方法。

    [Export("IsSwitchedOn")]
    public bool IsSwitchedOn() {
        return IsOn;
    }

比你可以像这样访问 UiTest 中的方法。

app.Query(x => x.Id("CustomView").Invoke("IsSwitchedOn"));

推荐阅读