2016-09-18 9 views
0
안드로이드

에서 버튼의 GET 크기가 나는 XML 파일 (DP에서) 크기를 설정하는 버튼이있는 경우 :잘못된 값을 다음과 같이

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" 
    > 

    <FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginLeft="0dp" 
     android:layout_marginRight="0dp" 
     android:layout_marginTop="80dp" 
     android:layout_marginBottom="80dp" 
     android:layout_centerInParent="true" 
     > 

     <Button 
      android:id="@+id/btn1" 
      android:layout_width="10dp" 
      android:layout_height="10dp" 
      android:scaleType="fitCenter"/> 

     <Button 
      android:id="@+id/btn2" 
      android:layout_width="50dp" 
      android:layout_height="50dp" 
      android:scaleType="fitCenter"/> 
    </FrameLayout> 
</RelativeLayout> 

내가 버튼의 크기를 얻을 수 getWidth() and getHeight() of View returns 0에서 답을 따랐다. 그러나 10dp 및 50dp 대신 잘못된 값 300,300을 반환합니다. 내 코드는 어떻게됩니까? 감사합니다 모두

Button btn=(Button) findViewById(R.id.btn1); 
btn.measure(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); 
width_btn = btn.getMeasuredWidth(); 
height_btn = btn.getMeasuredHeight(); 
Log.d("TAG", String.valueOf(index)+String.valueOf(width_btn)+","+String.valueOf(height_btn)); 
+1

'getMeasured *()'메소드가 아닌'getWidth()'와'getHeight()'를 사용해야합니다. 또한'Button'에서'measure()'를 호출하면 안됩니다. –

+0

해결책을 제공해 주시겠습니까? 'onWindowFocusChanged'에서'getWidth()'와'getHeight()'메소드를 호출하려했으나 어플리케이션이'onWindowFocusChanged'로 이동하지 않았습니다 – Jame

+0

그래, 그 방법이 싫어. 내가 발견했다. 저는 항상 __2에 설명 된 방법을 사용합니다. 레이아웃 큐에 runnable을 추가하십시오 : [이 대답은] (http://stackoverflow.com/a/24035591)의 View.post() __. 'Button','post()'에'Runnable'을 찾아 내서 그 너비/높이를 가져옵니다. 예를 게시 할 수 있습니다. 나중에 작동하도록 할 수 없으면 먼저 시도해보십시오. 내 대답은 실제로 그 예와 거의 흡사합니다. –

답변

2

레이아웃 파일에서 버튼 높이와 너비가 고정되어 있음이 분명합니다. 다음과 같이 dimens.xml 파일에서 버튼의 폭과 높이를 정의 할 수 있습니다

<dimen name="btn_width">50dp</dimen> 
<dimen name="btn_hieght">10dp</dimen> 
이제 폭을 얻을 수있는 지금

android:layout_width="@dimen/btn_width" 
android:layout_height="@dimen/btn_hieght" 

레이아웃 이러한 높이와 너비를 설정

와 높이를

float hieght = getResources().getDimension(R.dimen.btn_hieght); 
float width = getResources().getDimension(R.dimen.btn_width); 

마이크가 제안했듯이 btn.measure 행을 삭제하십시오. 당신이 getWidth getMeasureWidth.the보기를 사용할 때 mesure 수, 레이아웃, 그리기 때문이 값을 onPause하는

+0

감사합니다. 그것은 내가 필요한 것입니다. – Jame

0

추가 코드는 0 되지 않습니다.