gpt4 book ai didi

android - TypedArray.getInteger() 和 TypedArray.getInt() 有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:04 26 4
gpt4 key购买 nike

查看 TypedArray ( link ) 的源代码,我似乎无法弄清楚这两种方法之间的区别。 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。不同之处在于他们如何处理这两种情况。

来自link :

/*
* 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 将返回默认值。

另请注意,在这种奇怪的情况下,它们的行为差异很大,以至于在每种情况下都称一个优于另一个是不正确的。最好的解决方案是符合您对失败的预期的解决方案。

关于android - TypedArray.getInteger() 和 TypedArray.getInt() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14163682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com