JasonAddFour
JasonAddFour

Reputation: 163

Aligning two TextViews one after another (accounting for first textview to be very long)

I am trying create a layout that puts two TextViews one after another. Would the best option be to just use one TextView instead and just concatenate the strings and somehow style one part bold?

Currently I get weird effects where one TextView might get squished unless I use weights.

Examples of what I would want:


[first text view ] [ second text view]


[first text view really really really reallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreally long] [second text view]


[first text view ] [secod text view really really really reallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreallyreally long]


<LinearLayout
    android:id="@+id/Names"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_alignParentTop="true"
   android:layout_toRightOf="@+id/ivProfileImage"
    >

    <TextView
        android:layout_marginLeft="10dp"
        android:gravity="center"
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Namedsfsfsafsafsadfasfsadffddsfsfdsfdssafsafa fdsfds"
        android:textStyle="bold" />

    <TextView
        android:layout_marginLeft="10dp"
        android:gravity="left|center"

        android:id="@+id/tvUserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="none"
        android:layout_weight="1"
        android:text="fdfds@usernamestuff dsfdsfsdfsdsdfdsfdsdsfsdfsfds" />
</LinearLayout>

With this layout what I am seeing is the text views are essentially taking up half the layout width (when text is long) and not flowing naturally. It looks a bit weird:

[first view really long.....| [ scond view on this side]

breaks up like this]........|

Upvotes: 0

Views: 333

Answers (1)

A. AMAIDI
A. AMAIDI

Reputation: 6849

The described bahavior can be achieved using SpannableString as demonstrated in this Sample

SpannableString styledString
  = new SpannableString("Large\n\n"     // index 0 - 5
       + "Bold\n\n"                     // index 7 - 11
       );   

 // make the text twice as large
 styledString.setSpan(new RelativeSizeSpan(2f), 0, 5, 0);

 // make text bold
 styledString.setSpan(new StyleSpan(Typeface.BOLD), 7, 11, 0);

 // use the created string 
 textView.setText(styledString);

This way you use just one TextView and you'll avoid managing different views. just handle your string as you wish then display it within your TextView

Upvotes: 1

Related Questions