【发布时间】:2015-08-28 14:37:12
【问题描述】:
我正在 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();
}
}
问题是obtainStyledAttributes并没有获取所有的属性,即使它们存在于属性集中。更奇怪的是,如果我更改 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 个案例的手表窗口的 2 个屏幕截图。断点是在 try 语句之后设置的。
无论如何,如果我一次获得一个属性,它对所有属性都有效。 gainStyledAttributes 是如何工作的?另外我不确定是否应该使用 styledAttrs.getIndex(i) 函数,但这是解决当前问题后的问题。
【问题讨论】:
标签: java android android-custom-view