按鈕獲取大小我在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));
您應該使用'getWidth()'和'getHeight()',而不是'getMeasured *()'方法。你也不應該在'Button'上調用'measure()'。 –
你能否提供解決方案?我試圖在'onWindowFocusChanged'中調用'getWidth()'和'getHeight()'方法,但該應用程序不會去'onWindowFocusChanged' – Jame
是的,我不喜歡這種方法,因爲它不是很可靠,至於我找到了。我總是使用__2中描述的方法。添加一個可運行的佈局隊列:View.post()__ [此答案有](http://stackoverflow.com/a/24035591)。找到你的'Button','post()''Runnable',並獲得寬度/高度。我可以發佈一個例子,如果你不能爲它工作,但請先嚐試一下。我的答案實際上就像那裏的例子。 –