Bor*_*jev 5 android android-custom-view android-custom-attributes
我试图android从我的代码中获取命名空间的几个样式属性.在这里,我附上相关的摘录.AttributeSet attrs是传递给任何自定义的参数TextView.
private static final int[] ATTRS = new int[] { android.R.attr.textSize,
android.R.attr.text, android.R.attr.textColor,
android.R.attr.gravity };
private void processAndroidAttributes(final Context context,
final AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
try {
final String text = a.getString(1);
myTextView.setText(text);
final float textSize = a.getDimensionPixelSize(0, DEFAULT_TEXT_SIZE);
myTextView.setTextSize(textSize);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我想阅读4中描述的4个属性int[] ATTRS.如你所见,我把它textSize作为这个数组的第一个元素.原因很简单 - 如果我将它换成数组中的第二位,则其值无法正确读取(而是加载提供的默认值).另一方面,文本正确地加载到ATTRS我放置它的数组中的任何位置.我不敢跟的位置偏好试验gravity和textColor,但这种排列他们不工作.
有人可以解释为什么获得行为的不稳定行为?
Bor*_*jev 10
这似乎是API中的一个错误.我做了测试,4个属性:gravity,text,textSize和textColor.这是我使用的代码:
private void processAndroidAttributes(final Context context, final AttributeSet attrs) {
ATTRS = new Integer[] {
android.R.attr.textSize, android.R.attr.text,
android.R.attr.textColor, android.R.attr.gravity };
Arrays.sort(ATTRS);
do {
printPermutation(ATTRS);
tryApplyingStyles(context, attrs, ATTRS);
ATTRS = nextPermutation(ATTRS);
} while ((ATTRS = nextPermutation(ATTRS)) != null);
}
Run Code Online (Sandbox Code Playgroud)
该方法processAndroidAttributes尝试应用所有列出的属性,并检查它们是否已应用或使用了默认值.对于每次迭代,我打印数组ATTRS内容以及是否使用了实际值(标记为1)或使用了默认值(标记为0).以下是我运行上面代码后得到的结果(每次迭代打印几行):
[16842901,16842904,16842927,16843087]
1111
[16842901,16842904,16843087,16842927]
1110
[16842901,16842927,16842904,16843087]
1101
[16842901,16842927,16843087,16842904]
1101
[16842901,16843087,16842904,16842927]
1100
[16842901,16843087,16842927,16842904]
1100
[16842904,16842901,16842927,16843087]
1011
[16842904,16842901,16843087,16842927]
1010
[16842904,16842927,16842901,16843087]
1011
[16842904,16842927,16843087,16842901]
1011
[16842904,16843087,16842901,16842927]
1010
[16842904,16843087,16842927,16842901]
1010
[16842927,16842901,16842904,16843087]
1001
[16842927,16842901,16843087,16842904]
1001
[16842927,16842904,16842901,16843087]
1001
[16842927,16842904,16843087,16842901]
1001
[16842927,16843087,16842901,16842904]
1001
[16842927,16843087,16842904,16842901]
1001
[16843087,16842901,16842904,16842927]
1000
[16843087,16842901,16842927,16842904]
1000
[16843087,16842904,16842901,16842927]
1000
[16843087,16842904,16842927,16842901]
1000
[16843087,16842927,16842901,16842904]
1000
[16843087,16842927,16842904,16842901]
1000
Run Code Online (Sandbox Code Playgroud)
如您所见,这几乎就像期望对数组进行排序一样,只有几个异常值.我认为这是Android API中的一个错误,因为文档obtainStyledAttributes中没有指定任何属性ID的排序.
| 归档时间: |
|
| 查看次数: |
9848 次 |
| 最近记录: |