Android UI: Smart Center?

So, I have a user interface element (a single line of text) that I want horizontally with respect to the general device - if / until it encounters other interface elements in this group of views / layout. At this moment, I would like it to be concentrated in the space that remains, or tied as close to the center as possible, without a collision. [When there is ultimately not enough space, then I want to use ellipses.]

Is there a way to achieve this using only standard Android layouts?

I am currently achieving this with code that adjusts layout limitations when changing the width of the view group, changing text, or related user interface elements, becomes visible / invisible. It works great, but I can't help but think that some kind of layout should just do it for me.

+4
source share
1 answer

You can use weighted horizontal LinearLayout, like this:

<LinearLayout
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <TextView
        android:gravity="center_horizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="i am centered"
        android:ellipsize="end"
        />

    <Button
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="another widget"/>
     .
     .
     .
</LinearLayout>

TextViewwith a width of 0dp and a weight of 1 will use the remaining horizontal space.

You can add additional widgets to LinearLayout, and TextViewwill always occupy the remaining space.

, Button GONE, , TextView , . , LinearLayout, TextView.

ellipsize, , , TextView.

0

Source: https://habr.com/ru/post/1675799/


All Articles