Search code examples
androidandroid-custom-viewandroid-constraintlayout

Custom View not adhering to Constraints in Constraint Layout


I have a custom FrameLayout in my project which acts as a button since I did not want to to keep repeating same code. The view works perfectly but when I need to arrange them horizontally constraining to each other, The center view does not follow the constraints and instead, It aligns to parent start overshadowing the other. What should I do to my code to ensure the constraints work as expected? The code is as below

dash_buttons.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <com.revosleap.wazalendo.utils.ui.DashButton
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/dashButtonLoan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:dash_text="Pay"
            app:dash_icon="@drawable/ic_pay"
            android:id="@+id/dashButtonPay"
    />
    <com.revosleap.wazalendo.utils.ui.DashButton
            app:layout_constraintStart_toEndOf="@id/dashButtonPay"
            app:layout_constraintEnd_toStartOf="@id/dashButtonAccount"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:dash_text="Loan"
            app:dash_icon="@drawable/ic_loan"
            android:id="@+id/dashButtonLoan"

    />
    <com.revosleap.wazalendo.utils.ui.DashButton
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toEndOf="@id/dashButtonLoan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:dash_text="Account"
            app:dash_icon="@drawable/ic_user"
            android:id="@+id/dashButtonAccount"
    />
</android.support.constraint.ConstraintLayout>

The result

The result I get


Solution

  • I finally figured it out. It seems Constraint Layout has some issues with custom views that use layout resource containing Linear Layout. To achieve my objective, I changed parent layout from Constraint layout to Frame layout and used gravity to maintain positions and all runs perfectly now.