Xamarin.Android类库自定义视图无法使用declare-styleable自定义属性
解决Xamarin.Android类库中自定义视图declare-styleable属性无法识别的问题
我之前在做Xamarin.Android类库复用自定义视图时,也碰到过完全一样的问题,核心是类库的自定义属性不能直接用res-auto命名空间,做以下几个调整就能解决:
1. 替换XML命名空间,使用类库实际包名
你当前用的xmlns:app="http://schemas.android.com/apk/res/res-auto"只适用于主应用项目的自定义属性,类库的资源有独立的包名,必须明确指定。
比如你的自定义视图是Core.MyCustomView,那类库的包名应该是Core,把布局里的命名空间改成:
xmlns:app="http://schemas.android.com/apk/res/Core"
如果你的类库包名不是Core,可以去类库项目的属性 -> Android Manifest里查看实际的Package Name,替换掉上面的Core即可。
2. 确保自定义视图构造函数正确读取属性
在MyCustomView类中,需要在构造函数里通过TypedArray获取自定义属性值,示例代码如下:
public MyCustomView(Context context, IAttributeSet attrs) : base(context, attrs) { // 获取自定义属性对应的TypedArray var typedArray = context.ObtainStyledAttributes(attrs, Resource.Styleable.MyCustomView); // 读取srcLittle属性的资源ID,第二个参数是默认值 int srcLittleResId = typedArray.GetResourceId(Resource.Styleable.MyCustomView_srcLittle, 0); if (srcLittleResId != 0) { // 根据你的需求设置资源,比如给内部ImageView设置图片 // innerImageView.SetImageResource(srcLittleResId); } // 务必回收TypedArray,避免内存泄漏 typedArray.Recycle(); }
3. 清理并重建整个解决方案
Xamarin的资源同步偶尔会有延迟,执行以下步骤确保资源正确生成:
- 右键解决方案 -> Clean Solution
- 右键解决方案 -> Rebuild Solution
做完这些调整后,XML里的app:srcLittle="@drawable/ic_plane"就能正常识别,编译错误也会消失了。
内容的提问来源于stack exchange,提问作者JonZarate
相关产品推荐
相关产品推荐

