从视图膨胀过程获取IAttributeSet

问题描述 投票:0回答:1

我正在研究一个项目,该项目依赖于用户向其Android布局元素中添加自定义属性。就像MvvmCross的app:MvxBind。没有自定义视图类,因为其想法是用户可以使用普通的Android视图。

问题是,为了获得此标记的值,我需要获取在视图膨胀过程中使用的IAttributeSet,但我找不到适合自己需求的方法。

[我有一个使用LayoutInflater.IFactory的工作示例,但是这需要我设置自己的LayoutInflater / factory,如果用户使用的是MvvmCross之类的库,则会导致问题,因为一次只能设置一个工厂。

[我正在寻找一种方法,每当视图放大时,我都可以获取IAttributeSet对象,以检查我的属性,该属性不会干扰其他库中的标准LayoutInflater或LayoutInflater。或者,如果视图膨胀后,是否有任何方法可以获取我的属性。

提前感谢!

android xamarin attributes mvvmcross inflate
1个回答
0
投票

我不确定我是否理解你的意思。请参考以下内容:

您可以创建一个自定义视图,并在attrs.xml中定义其属性,当从XML布局创建它时,将从资源束中读取XML标记中的所有属性,并将其作为IAttributeSet传递到视图的构造函数中]

例如,这是一个名为IconView的自定义视图

public class IconView : View
{
}

attrs.xml中定义一些属性(资源/值/attrs.xml

<declare-styleable name="IconView">
  <attr name="bg_color" format="color" />
  <attr name="src" format="integer" />
  <attr name="showIconLabel" format="boolean" />
  <attr name="iconLabelTextColor" format="color" />
  <attr name="iconLabelText" format="string" />
</declare-styleable>

然后,我们可以在创建视图构造函数时处理它的属性(在这里定义一个Initialize方法):

public IconView(Context context) : base(context)
{
  Initialize(context);
}

public IconView(Context context, IAttributeSet attrs) : base(context, attrs)
{
  Initialize(context, attrs);
}

private void Initialize(Context context, IAttributeSet attrs = null)
{
  if (attrs != null)
  {
    // Contains the values set for the styleable attributes you declared in your attrs.xml
    var array = context.ObtainStyledAttributes(attrs, Resource.Styleable.IconView, 0, 0);

    iconBackgroundColor = array.GetColor(Resource.Styleable.IconView_bg_color, Color.Gray);
    iconLabelTextColor = array.GetColor(Resource.Styleable.IconView_iconLabelTextColor, Color.ParseColor("#D9000000"));
    _labelText = array.GetString(Resource.Styleable.IconView_iconLabelText);
    _showIconLabel = array.GetBoolean(Resource.Styleable.IconView_showIconLabel, false);

    var iconResId = array.GetResourceId(Resource.Styleable.IconView_src, 0);
    if (iconResId != 0) // If the user actually set a drawable
        _icon = AppCompatDrawableManager.Get().GetDrawable(context, iconResId);

    // If the users sets text for the icon without setting the showIconLabel attr to true
    // set it to true for the user anyways
    if (_labelText != null) 
        _showIconLabel = true;

    // Very important to recycle the array after use
    array.Recycle();
  }

     ...
}

您可以参考它以获取更多详细信息make custom view

© www.soinside.com 2019 - 2024. All rights reserved.