我正在Android中创建自定义视图。在它的构造函数中,我获得了XML布局文件中设置的一些属性。代码是这样的:
public LabeledEditText(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray styledAttrs = context.getTheme().obtainStyledAttributes(attrs, new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }, 0, 0);
try {
int id = styledAttrs.getResourceId(styledAttrs.getIndex(0), -1);
String digits = styledAttrs.getString(styledAttrs.getIndex(1));
float padding = styledAttrs.getDimension(styledAttrs.getIndex(2), 0.1f);
int inputType = styledAttrs.getInt(styledAttrs.getIndex(3), -1);
} finally {
styledAttrs.recycle();
}
}
问题在于即使这些属性存在于属性集中,其均不会获得所有属性。甚至更奇怪的是,如果我更改int数组中id的顺序,则会得到不同的结果。例如,如果我使用以下顺序
new int[] { android.R.attr.id, android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType }
我得到3个属性,但是如果我使用以下顺序
new int[] {android.R.attr.digits, android.R.attr.padding, android.R.attr.inputType, android.R.attr.id }
我回来2。我包括这2个案例的watchs窗口的2个屏幕截图。断点是在try语句之后设置的。
在任何情况下,如果我一次获得一个属性,则对所有这些属性都有效。getsStyledAttributes如何工作?另外,我不确定是否应该使用styledAttrs.getIndex(i)函数,但是在解决了当前函数之后,这是一个问题。
尽管没有记录,但obtainStyledAttributes
需要一个有序数组,并在此假设下对其代码进行了优化。
因此,您需要为styledAttrs
数组提供根据其id值以升序排列的元素。
有几种方法可以确定正确的顺序:
如果选择在运行时以编程方式对数组进行排序,请确保在调用getString()
etc时使用适当的(排序的)索引。
另一个常见的解决方法是一次仅获取一个值obtainStyledAttributes
。(具有一个元素的数组已经排序。)
另外我不确定是否应该使用styledAttrs.getIndex(i)函数
我认为只有在您遍历TypedArray
且可能其中某些元素可能没有值时,这才是必要的;它基本上为您“隐藏”了null元素,就好像它是一个稀疏数组一样。通常,除非您以某些方式(例如在实现自定义视图时)访问样式化的资源,否则我认为没有必要。
大多数时候,我使用与视图完全无关的自定义主题属性,在这些情况下,我总是觉得TypedArray.getIndex()
多余。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句