9

查看 TypedArray 的源代码(链接),我似乎无法弄清楚这两种方法之间的区别是什么。getInt()与 基本相同getInteger(),但最后有一个我不明白的小补充。有人可以向我解释吗?

我需要知道区别的原因是我正在实现一个自定义的 Preference 子类,并获得我需要 override 的默认值onGetDefaultValue(),它从 TypedArray 中获取一个整数。例子:

@Override
protected Object onGetDefaultValue(TypedArray a, int index)
{
    return a.getInteger(index, DEFAULT_VALUE);
}

我在这里使用getInteger(),但如果getInt()更好,那么我将使用它。

4

1 回答 1

8

他们只是有不同的“一切都失败了”的情况。他们都返回int一个有效的intdefValuenull不同之处在于他们如何处理这两种情况。

链接

/*
 * 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. 相反,如果所有其他方法都失败,则getInt返回默认值。

Also note that the behavior of them in this odd case is different enough that calling one superior to the other in every case would be incorrect. The best solution is the one that matches your expectations for failure.

于 2013-01-04T19:44:40.233 回答