yazan sayed
yazan sayed

Reputation: 1139

ViewGroup layoutParams in android

i have a simple layout containing an ImageView and a TextView, here's how the ImageView looks like

<ImageView
        android:id="@+id/imageView4"
        android:layout_width="50dp"

        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/BottomViewGroup"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/circle" />
I purposely made the width 50dp.

in the mainActivity i'm playing with layoutParams

val params= imageView4.layoutParams
textView.text=params.width.toString()
        

now when i run the app , the TextView says 150 ,shouldn't it say 50 ?

Upvotes: 0

Views: 79

Answers (1)

TylerQITX
TylerQITX

Reputation: 328

The width 150 is px, the 50 is dp.

public int convertPxToDp(Context context, int px) {
    return (int)(px / context.getResources().getDisplayMetrics().density);
}   
public int convertDpToPx(Context context, int dp) {
    return  (int)(dp * (context.getResources().getDisplayMetrics().density));
}

Upvotes: 1

Related Questions