2016-09-18 64 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视图不能进行布局绘制时。