2013-10-17 2 views
0

내 활동에서 뷰의 크기를 파악하려고합니다.보기의 크기를 쿼리해도 안전합니까?

<com.example.dragdropshapes.CustomStrechView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/border" 
    android:src="@drawable/missingpuz" 
    android:clickable="true" 
    android:onClick="pickShapes" 
    /> 

내가 특정 "fill_parent"가 될 수있을 테니까요 알 필요가 : 뷰는 이미지 뷰를 확장하는 간단한 사용자 지정보기입니다. 내 사용자 지정보기가 포함 된 레이아웃을 사용하여 활동의 onCreate 방법 중에이 정보를 얻기 위해 시도 :이 경우

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_puzzle_picker); 
    // Show the Up button in the action bar. 
    setupActionBar(); 
    int a = findViewById(R.id.pickshapes).getMeasuredHeight(); 
    int b = findViewById(R.id.pickshapes).getHeight(); 

모두 a을하고 나중에 0의 값을 반환 b, 사용자 지정보기가 사용됩니다 버튼이 (그것이 온 클릭 핸들러가) 그래서 핸들러의 크기를 얻기 위해 다시 시도 할 생각으로 :

public void pickShapes(View view){ 
    Intent intent = new Intent(this, ShapesActivity.class); 
    int a = findViewById(R.id.pickshapes).getMeasuredHeight(); 
    int b = findViewById(R.id.pickshapes).getHeight(); 
    startActivity(intent); 
} 
다음

ab 모두 유효한 치수를주고 ... 나는 기다릴 싶지 않아 그러나 "onClick"이벤트는 po만큼 빨리 차원을 가져 오려고합니다. 도움이된다. 나는 onStart()onResume()을 모두 오버라이드하여 크기를 확인해 보았습니다.하지만 두 경우 모두 여전히 0이됩니다.

Android 활동 시작 흐름에서 가장 먼저 얻을 수있는 부분은 제 질문입니다. 보기의 실제 크기? 가능한 한 빨리 높이/너비를 가져올 수 있기를 원합니다. 사용자가 환경과 상호 작용할 수 있기 전에이를 수행하고 싶습니다.

답변

2

안드로이드에는 ViewTreeObserver이라는 매우 유용한 것이 있습니다. 이런 식으로 여러 번해야 할 일을 정확하게 수행했습니다. 발견 한대로 적어도 측정주기가 완료 될 때까지 기다려야합니다. 다음과 같이하십시오 : (. 그건 당신이 선택한 무엇 때문에 당신이 당신의 XML에서 뷰의 ID를 설정하지 않은 있습니다 ... 내가 R.id.pickshapes을 사용하고 있습니다)

... 
setContextView(R.layout.activity_puzzle_picker); 

final View view = findViewById(R.id.pickshapes); 
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     int height = view.getMeasuredHeight(); 
     if(height > 0) { 
      // do whatever you want with the measured height. 
      setMyViewHeight(height); 

      // ... and ALWAYS remove the listener when you're done. 
      view.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
     }       
    } 
}); 
... 

+0

옙,이 정답은 +1입니다. – Carnal

+0

그게 정말 멋지다. 정확히 내가 필요로하는 것이었다. API 레벨 16 이전에'removeOnGlobalLayoutListener()'대신에 무엇을 했는가? – Mike

+0

발견,'On'은 그 팅겨보고있는 오래된 API (즉'removeGlobalOnLayoutListener()')의'Global'의 반대편에 있으며, SDK 버전에 대한 확인이 끝났습니다! 매우 감사합니다! – Mike