Center a button and a TextView with ellipsis in Android

143 views Asked by At

I have following code with a TextView and a Button and I want them to be centered. The problem occurs when the text is too long so it pushes the button off the screen even if I use ellipsis. I do not want to use layout_weight because it adds extra space around the button and it looks like right aligned, but probably I am not doin it well in this case either.

<LinearLayout
   android:id="@+id/id1"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:orientation="horizontal">

   <TextView
      android:id="@+id/id2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:ellipsize="end"
      android:maxLines="1"
      android:textAlignment="center" />

   <ImageButton
      android:id="@+id/id3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:srcCompat="@drawable/myDrawable" />
</LinearLayout>

It looks like this when the text is too long:

*--------------------------*
*Looooooooooooong te... But*
*--------------------------*

Using weights looks something like this:

*--------------------------*
*    TextView.      Button *
*--------------------------*

I want it to look something like this when the text is too long:

*--------------------------*
*Loooooooooonoooo... Button*
*--------------------------*

and something like this when the text is not very long:

*--------------------------*
*         Text Button      *
*--------------------------*
1

There are 1 answers

1
Mahdi On

how about handle the size of the textView programmaically? so you can set a maximum size for your textview based on the button

for example if you want to set 13 char for max size, it will be somthing like this:

String longText;
 if (data.length() >= 13) {
        longText= data.substring(0, 13)+ "...";

 } else {

        longtext = data;

}
    textView.setText(longText);