【发布时间】: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