TextView go to new line in space

Viewed 546

I have a TextView with a text composed of two words, where the second is dynamic (like "Number of device: xxxxxxxxxxxx". I want that if the String is too long, it will display like

Number of device:
xxxxxxxxxxxx

Now it is like

Number of device: xxxxxxx
xxx
<TextView
                android:id="@+id/ObuTransitElementObuDeviceCode"
                android:layout_marginTop="6dp"
                android:layout_marginStart="16dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/empty_text_placeholder"
                android:breakStrategy="balanced"
                android:textAlignment="textEnd" />
2 Answers

You need to observe layout changes in this case since the due to height change the bottom value will be changed if the text set to two line.

work with wrap_content only

TextView tvDevice = findViewById(R.id.ObuTransitElementObuDeviceCode);
tvDevice.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if(bottom != oldBottom){
                    String s = tvDevice.getText().toString();
                    if(!s.contains("\n"))tvDevice.setText(s.replace(":",":\n"));
                }
            }
        });
tvDevice.setText("Number of device:\n"+dynamic_number);

just do :

TextView tv = findViewById(R.id.ObuTransitElementObuDeviceCode);
tv.setText("Number of device:\n"+dynamic_number);
Related