【问题标题】:Android - How to detect parent layout typeAndroid - 如何检测父布局类型
【发布时间】:2016-11-19 19:24:23
【问题描述】:

我正在使用以下代码:

        String[] UIItems = new String[5];
        UIItems[0] = "game_area_holder";
        UIItems[1] = "topListBtn";
        UIItems[2] = "bigBtn";
        UIItems[3] = "reposBtn";
        UIItems[4] = "sectorStateColorLine";
        for (int number = 0; number < UIItems.length; number++) {
            itemID = getResources().getIdentifier(UIItems[number],"id",getPackageName());

            ImageView aktUIItem = (ImageView) findViewById(itemID);

            FrameLayout.LayoutParams aktUIItemParams = (FrameLayout.LayoutParams)aktUIItem.getLayoutParams();
 .
 . doing things here with aktUIItemParams
 .
 }

这很好用,但如果我将其中一个图像放入另一个布局(线性、相对等),则会收到一条错误消息:

java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams 无法转换为 android.widget.FrameLayout$LayoutParams

当然,这是因为父级不是 FrameLayout...但是如何以编程方式检查图像的父级布局类型?或者如何将 getLayoutParams() 转换为“标准”LayoutParams?

【问题讨论】:

  • "或者如何将 getLayoutParams() 转换为“标准”LayoutParams?” ViewGroup.LayoutParams ?
  • 差不多好了,但是如果我使用 ViewGroup.LayoutParams,那么 aktUIItemParams.leftMargin 不可用... :((对不起,我之前没有写...我需要访问 getIntrinsicWidth () 和 ...Height() 以及项目 leftMargin 和 topMargin 属性)
  • 我知道您已经有了一个可以接受的答案,但ViewGroup.MarginLayoutParams 有可能包含您需要的所有方法/字段。如果是这样,那么您将能够避免任何强制转换。
  • 哦,是的,这确实比公认的方法更好......对不起,但还是谢谢!

标签: java android android-layout


【解决方案1】:

如果ViewGroup.LayoutParams 不适合你,那么你需要到instanceof 检查布局参数是否属于你可以使用的类型:

ViewGroup.LayoutParams layoutParams = aktUIItem.getLayoutParams();

if (layoutParams instanceof FrameLayout.LayoutParams) {
  FrameLayout.LayoutParams frameLayoutParams = (FrameLayout.LayoutParams)layoutParams;
  ...// do that old school logic
}
// ignore layoutParams or do another instance of check.

我建议您查看 Google 文档 PPartisan 链接 (here) 中列出的子类(直接和间接),以确定哪些子类提供您需要调用的方法。然后调用仍然具有您需要的方法的最超类。这样可以最大限度地减少所需的 instanceof 检查次数。

【讨论】:

    【解决方案2】:

    我在不知道父级的情况下更改布局边距时遇到了同样的问题,解决方案如下

    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) containerLayout.getLayoutParams();
            lp.setMargins(0, 0,0, Helper.getDPI(8,context));
            containerLayout.setLayoutParams(lp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多