我在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>
有什么问题吗?为什么我没有将我的View设置的id设置为firstViewReference?
提前致谢。
答案 0 :(得分:0)
此代码:
TypedArray a = this.Context.ObtainStyledAttributes(this.xmlAttrs, Resource.Styleable.CustomControl);
int aid =a.GetResourceId(Resource.Styleable.CustomControl_firstViewReference,0);
在OnFinishInflate中,因为我的观点需要访问它的孩子所以我必须等到它完成膨胀。
我将该代码放在视图构造函数中,现在它返回正确的id。
当然我需要在OnFinishInflate中调用findViewById,否则它将返回null。
解决方案是在构造函数而不是OnFinishInflate上创建TypedArray,有人可以指出为什么需要它吗? this.xmlAttrs是构造函数中收到的AttributeSet。