【问题标题】:Android custom control xml id referenceAndroid自定义控件xml id参考
【发布时间】:2016-02-22 06:55:38
【问题描述】:

我正在用 C# 为 Xamarin/Android 创建一个自定义控件

它需要在 xml 布局中设置对他们的 2 个孩子的引用,所以我尝试了这个。

  <declare-styleable name="CustomControl">
    <attr name="firstViewReference" format="reference" />
    <attr name="SecondViewReference" format="reference" />
  </declare-styleable>

然后在我这样做的代码中检索值:

   TypedArray a = this.Context.ObtainStyledAttributes(this.xmlAttrs, Resource.Styleable.CustomControl);
   int aid =a.GetResourceId(Resource.Styleable.CustomControl_firstViewReference,0);

但对 getResourceId 的调用总是返回错误值(此处为 0)。

我的 xml:

    <CustomControl xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:local="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        local:firstViewReference="@+id/firstView">
    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@id/firstView"/>
    </CustomControl>

有什么问题吗?为什么我没有将我的视图设置为 firstViewReference 的 id?

提前致谢。

【问题讨论】:

  • 什么是this.xmlAttrs?发布更多代码,因为现在不清楚您在哪里使用ObtainStyledAttributes

标签: c# android xml xamarin


【解决方案1】:

这段代码:

 TypedArray a = this.Context.ObtainStyledAttributes(this.xmlAttrs, Resource.Styleable.CustomControl);
   int aid =a.GetResourceId(Resource.Styleable.CustomControl_firstViewReference,0);

在 OnFinishInflate 中,因为我的视图需要访问它的子视图,所以我必须等到它完成膨胀。

我将该代码直接放在视图构造函数中,现在它返回了正确的 id。

当然我需要在 OnFinishInflate 中调用 findViewById 否则它会返回 null。

解决方案是在构造函数上创建 TypedArray 而不是 OnFinishInflate ,有人可以指出为什么需要这样做吗? this.xmlAttrs 是构造函数中接收到的 AttributeSet。

【讨论】:

  • 这是因为LayoutInflater 在夸大所有视图时共享相同的AttributeSet
  • 所以我只能在它开始解析下一个元素之前获取属性?不应该在文档中吗?
  • 是的,它应该是,但你知道......他们会这样做“mañana”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
相关资源
最近更新 更多