为什么的LinearLayout instance.getLayoutParams期待有一个错误的类?有一个、期待、错误、LinearLayout

2023-09-04 08:54:33 作者:柠萌味的小仙女

如果我宣布的LinearLayout LinearLayout中看看 linearLayout.getLayoutParams(),它给了我 ViewGroup.LayoutParams ,不是 LinearLayout.LayoutParams

If I declare LinearLayout linearLayout and look at linearLayout.getLayoutParams(), it gives me ViewGroup.LayoutParams, not LinearLayout.LayoutParams.

所以我必须使用的重复(因此坏)作风建设:

So I have to use the repeating (and thus bad) style construction of:

int lm = ((LinearLayout.LayoutParams) linearLayout.getLayoutParams()).leftMargin?

难道我真的要使用它,如果我想达到的利润,例如?

Do I really have to use it, if I want to reach margins, for example?

这是我的Andr​​oid或Java或误解两者还是其他什么东西?

Is it my misunderstanding of Android or Java, or both or something else?

推荐答案

我觉得你对'的LayoutParams的理解不正确。视图的(或布局的)的LayoutParams 必须是'父视图的的LayoutParams的一个实例。

I think your understanding about 'LayoutParams' is incorrect. A view's (or layout's) LayoutParams must be an instance of 'the parent view's LayoutParams'.

例如,下面是在RelativeLayout的一个LinearLayout中。这LinearLayout中的的LayoutParams必须RelativeLayout.LayoutParams。这件事情使我们能够正确地设置属性,如centerInParent等。

For example, here's an LinearLayout in RelativeLayout. That LinearLayout's LayoutParams must be RelativeLayout.LayoutParams. This thing enables us to set the attributes properly, like 'centerInParent' and etc.

当你调用 getLayoutParams(),返回匹配于母公司的ViewGroup类型的LayoutParams的各种实例。因此,我们需要反复投下的视图的的LayoutParams类型时调用 getLayoutParams()

When you call getLayoutParams(), that returns various instance of LayoutParams that matches to parent ViewGroup type. As a result, we need to cast the type of a view's LayoutParams repeatedly when calling getLayoutParams().