user8430 user8430 - 2 months ago 6
Android Question

Wrong value when get size of button in android

I have a button which are set size (in dp) in XML file as follows:

<?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>


I followed the answer in getWidth() and getHeight() of View returns 0 to get size of button. However, it return a wrong value
300,300
instead of 10dp and 50dp. What is happen in my code? Thank all

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));

Answer

From layout file, it is clear that button height and width fixed. You can define button width and height in dimens.xml file as follows:

<dimen name="btn_width">50dp</dimen>
 <dimen name="btn_hieght">10dp</dimen>

Now set these height and width to layout

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

Now you can get width and height

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

As Mike suggest, remove btn.measure line.

Comments