Search code examples
androidandroid-linearlayoutpadding

Android 4 - LinearLayout Top and Bottom padding doesn't work


I have a LinearLayout with a TextView inside. The problem is that padding is not working correctly on Android 4. I test app on HTC One X emulator Android 4.4.2

My layout:

<LinearLayout
        android:id="@+id/msg_body"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/chat_msg_bg"
        android:elevation="2dp"
        android:orientation="vertical"
        android:padding="16dp"
        android:paddingLeft="16dp"
        android:paddingStart="16dp"
        android:paddingEnd="16dp"
        android:paddingRight="16dp"
        android:paddingTop="16dp"
        android:paddingBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="@+id/user_name"
        app:layout_constraintTop_toBottomOf="@+id/user_name"
        app:layout_constraintVertical_bias="0.0">

Now it looks like this:

enter image description here

Left and right padding is working, but Top and bottom isn't. What can cause this problem and is there a way to handle this? I've tried to set padding programmatically, but there was no effect. On other OS versions and devices this works fine.

UPD: How it should be:

enter image description here


Solution

  • Try giving padding pragmatically :

    layout.setPadding(left,top,right,bottom);
    

    This will take px as parameter. to convert from dp to px :

     Resources r = mContext.getResources();
     int px = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpmeasure, 
            r.getDisplayMetrics()
    );
    

    Just remove all padding from XML.

    Reference

    OR

    Add margin to textview inside linear layout. and remove padding in linear layout.