2016-09-18 51 views
0

按鈕獲取大小我在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的回答讓按鈕的大小。但是,它會返回錯誤的值300,300而不是10dp和50dp。我的代碼中發生了什麼?謝謝全部

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

您應該使用'getWidth()'和'getHeight()',而不是'getMeasured *()'方法。你也不應該在'Button'上調用'measure()'。 –

+0

你能否提供解決方案?我試圖在'onWindowFocusChanged'中調用'getWidth()'和'getHeight()'方法,但該應用程序不會去'onWindowFocusChanged' – Jame

+0

是的,我不喜歡這種方法,因爲它不是很可靠,至於我找到了。我總是使用__2中描述的方法。添加一個可運行的佈局隊列:View.post()__ [此答案有](http://stackoverflow.com/a/24035591)。找到你的'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); 

正如Mike建議,刪除btn.measure行。

+0

謝謝。這正是我需要的 – Jame

0

將代碼添加到onPause值不會爲0. 因爲當您使用getWidth getMeasureWidth.the視圖不能進行佈局繪製時。