使用 ViewGroup.LayoutParams 时的类型安全

Type safety when using ViewGroup.LayoutParams

方法 ViewGroup.addView 的第二个参数是 ViewGroup.LayoutParams。在许多情况下,您希望使用 RelativeLayout.LayoutParams 之类的子类,但令人恼火的是方法签名中没有 type-safety,因此以下所有编译都可以正常工作。

relativeLayout.addView(textView, new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

relativeLayout.addView(textView, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

relativeLayout.addView(textView, new FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));

这让我有点担心,因为很容易不小心提供错误的类型。 (我不明白为什么要这样设计,但这不是我的问题)。

显然,当布局 ViewGroup 时,所有 children 的 LayoutParams 必须在某个时候转换为适当的类型,以便读取任何额外的规则。我可以确定对于 ViewGroup 的所有标准子类,所有这些转换都是经过检查的转换(即遵循 instanceof),所以如果我提供错误的类型,我将永远不会得到 ClassCastException 在运行时?

Can I be sure that for all of the standard subclasses of ViewGroup that all of these casts are checked casts (i.e. follow an instanceof), so that if I supply the wrong type I will never get a ClassCastException at runtime?

我向你保证情况并非如此,至少在某些情况下并非如此。因提供错误的 LayoutParams 类型而获得 ClassCastExceptions 肯定会发生,因为当人们遇到这种情况时,我不得不在 Stack Overflow 上回答相当多的问题。

也就是说,在大多数情况下,此异常确实表示存在编码错误(相对于用户可能以某种方式触发的错误)。

如果你的问题是 "does addView() on subclasses of ViewGroup check for the proper type?",答案通常是 "no",因为 类 和 RelativeLayout 一样,不要覆盖 addView() 而只是使用继承的来自 ViewGroup.

的实施