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