看一下TypedArray( 链接 )的源代码,我似乎无法弄清楚这两种方法之间的区别是什么。 getInt()
与getInteger()
基本相同,但最后添加了一小部分,我不明白。 有人可以向我解释一下吗?
我需要知道区别的原因是我正在实现一个自定义的Preference子类,并获取我需要覆盖onGetDefaultValue()
的默认值,它从TypedArray中获取一个整数。 例:
@Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getInteger(index, DEFAULT_VALUE); }
这里我使用getInteger()
,但如果getInt()
更好,那么我将使用它。
他们只是有不同的“所有其他失败”案件。 它们都为有效的int
返回一个int
,为null
返回defValue
。 区别在于他们如何处理这两者的情况。
从链接 :
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ TypedValue v = mValue; if (getValueAt(index, v)) { Log.w(Resources.TAG, "Converting to int: " + v); return XmlUtils.convertValueToInt( v.coerceToString(), defValue); } Log.w(Resources.TAG, "getInt of bad type: 0x" + Integer.toHexString(type)); return defValue;
这是你指的额外。 它似乎是将未知值转换为字符串然后转换为整数。 如果您存储了"12"
或某个等效值,这可能很有用。
另外,如果getInteger
不为null
而不是int
,则抛出exception。 相反,如果所有其他方法都失败,则getInt
将返回默认值。
还要注意,在这种奇怪的情况下,它们的行为是不同的,在每种情况下调用一个优于另一个的行为都是不正确的。 最好的解决方案是符合您对失败的期望。