Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position views using percentage for top/left within container?

I am hoping to position views within a parent view using percentages, similar to what is possible with absolute positioning in CSS. In my scenario, I will have a variable and unpredictable number of views that will be positioned this way.

Here is an example, which represents 3 TextViews inside a square with the following positions:

1: Top 55%, Left 29%
2: Top 77%, Left 58%
3: Top 54%, Left 43%

Views with percentage positions

Is this best accomplished using custom drawing? Or is it possible to dynamically position views within a certain type of parent view given these percentages? If the former, how can I handle the text? And if the latter, what type of view should the parent be, and how should I go about setting these percentages?

like image 253
Jake Avatar asked Feb 16 '18 05:02

Jake


1 Answers

You could use a ConstraintLayout https://developer.android.com/training/constraint-layout/index.html

A constraint layout will allow you to position a view based on percentages like you want using horizontal and vertical bias. For example:

<android.support.constraint.ConstraintLayout
    android:id="@+id/constraint"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <TextView
        android:id="@+id/edition_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.33"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.33"
        android:background="@android:color/holo_purple"
        android:text="text"/>

</android.support.constraint.ConstraintLayout>

Just make sure the child view (the Textview) is constrained to the top and bottom so you can set vertical bias. And also start, end so you can set horizontal bias.

The result is this:

enter image description here

And this can be done programmatically also, see here for a good guide: http://www.zoftino.com/adding-views-&-constraints-to-android-constraint-layout-programmatically

like image 74
Eoin Avatar answered Nov 20 '22 14:11

Eoin