tolga
tolga

Reputation: 2800

Background with a percentage in Android Layout

What I want to achieve is, I want to draw a box which wraps a text. The background color will fill percentage of the wrapper and that percentage will be a variable.

How can I achieve this in Android layout?

(If this was an HTML project, I would set two divs (parent/child): Parent would be relative and child would be absolute. So that I would have positioned child div at the bottom and set height as percentage.)

enter image description here https://www.autodraw.com/share/5MLGMPAVWLNH

Upvotes: 1

Views: 285

Answers (1)

Thracian
Thracian

Reputation: 66879

You can use a ConstraintLayout and set app:layout_constraintHeight_percent of textView to any value between 0 and 1.

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:textSize="64sp"
            android:gravity="center_horizontal"
            android:text="Text"
            app:layout_constraintBottom_toBottomOf="parent"
            android:background="#f9d048"
            app:layout_constraintHeight_percent=".5"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 1

Related Questions