Search code examples
androidandroid-constraintlayout

constraintlayout - set a view padding depending on another view


I would like to know if I can set the title of TextView_1 to be centered of the parent view but ellipsize end against TextView_2 like picture below by using constraint layout. if the text in TextView_1 gets longer then, make it ellipsized. and below would be the case where I wanted to put "Text to be centered but ellipsize against TextView_2 when it gets longer".

what I have tried are

  1. I programmatically tried to get the width of TextView_2 and set it to padding right of TextView_1. but failed since I wasn't able to get the width of TextView_2(I get 0) since it is set to be 0dp in constraint layout to be stretched.
  2. I tried to find a way to set TextView_1 padding as TextView_2 size in xml file but that doesn't seem to be possible.

I have no more good idea to make it work. is there any work around for it? I will appreciate your help in advance.

centered_title_but_padding_against_other_textView


Solution

  • You didn't post code, but I don't think you waited for the layout to occur to get the size of textView2. Here is some working code with the following XML. The code runs in the onCreateView() function of the Fragment. After layout, the width of TextView2 is set to the start/left padding of TextView1.

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:text="Text to be centered but ellipsize against TextView_2 when it gets longer"
            android:textSize="16sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/textView2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="TextView2"
            android:textSize="16sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="@+id/textView1" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    binding = DataBindingUtil.setContentView(requireActivity(), R.layout.fragment_main)
    binding.root.doOnNextLayout {
        binding.textView1.updatePadding(binding.textView2.width)
    }
    

    enter image description here