2016-07-16 2 views
0

을 감지하는 방법 :안드로이드 - 나는 다음과 같은 코드를 사용하고 부모 레이아웃 유형

 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 ... 그러나 이미지의 부모 레이아웃 유형을 확인하려면 어떻게해야합니까? 와이? 또는 어떻게 "표준"LayoutParams에 getLayoutParams()를 캐스팅 할 수 있습니까? 나중에에 대한 ViewGroup.LayoutParams 실 거예요 작품은 다음을 참조하는 instanceof 확인에 필요합니다 경우 레이아웃 PARAMS이 유형의 경우

+0

"또는 어떻게 표준"LayoutParams "로 getLayoutParams()를 캐스팅 할 수 있습니까?" ['ViewGroup.LayoutParams'] (https://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html)? – PPartisan

+0

괜찮 았지만 ViewGroup.LayoutParams를 사용하면 aktUIItemParams.leftMargin을 사용할 수 없습니다. ... ( (죄송합니다. 이전에 작성하지 않았습니다 ... getIntrinsicWidth()에 대한 액세스 권한이 필요합니다 ... Height() 및 item leftMargin 및 topMargin 속성) – Zoltan

+0

이미 답변을 받았지만 ['ViewGroup.MarginLayoutParams'] (https://developer.android.com/reference/android/view) 가능성이 있습니다. /ViewGroup.MarginLayoutParams.html)에는 필요한 모든 메소드/필드가 포함됩니다. 그러면 캐스팅을 피할 수 있습니다. – PPartisan

답변

1

당신이 소비 할 수 있습니다 :

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 Apps의 PPartisan 링크 (here)에 나열되어있어 호출해야하는 메소드를 제공하는 하위 클래스를 결정합니다. 그런 다음 필요한 수퍼 클래스를 호출합니다. 그렇게하면 필요한 instanceof 검사의 수를 최소화 할 수 있습니다.

+0

고맙습니다, 잘 작동합니다! :) – Zoltan

관련 문제