Search code examples
androiduser-interfacetextviewalignmentandroid-relativelayout

Android two Textviews, align them as one paragraph


Lets say I have two textviews, a title, and details, the details is toEndOf the title (same line), and while the title is one line, the details, can be multiple, my question is, how can I configure the details textview that when it starts a new line, instead of aligning it to the previous row of the textview, align it to the title textview, hence creating a paragraph feel.

Please see these screenshot to understand what I'm trying to accomplish (the title is the bold text, details it the rest):

Desired: enter image description here

What I have so far:

enter image description here

The only solution I can think of is using one textview for both, and format the text with HTML, but what if I need a bigger text size for the title?

Thanks!


Solution

  • You can use SpannableText

    This will do the job!

     <TextView
        ..
        android:id="@+id/text_view"
        />
    

    ...

    TextView text=(TextView)findViewById(R.id.text_view);
    String head = "Seat (s):";
    String body = "  The  baby name  means  the meaning of the nam";
    setTextWithSpan(text,head+body,head, body,new android.text.style.StyleSpan(android.graphics.Typeface.BOLD));
    

    Custom method

    public  void setTextWithSpan(TextView textView, String text, String spanTextBold,String secondPartOfText,StyleSpan style) {
    
        SpannableStringBuilder sb = new SpannableStringBuilder(text);
    
        int start = text.indexOf(spanTextBold);
        int end = start + spanTextBold.length();
        sb.setSpan(style, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE );
        //sb.setSpan(new ForegroundColorSpan(Color.BLUE), start, end ,0); // if you need a color
    
        int startTwo = text.indexOf(secondPartOfText);
        int endTwo = startTwo + secondPartOfText.length();
        // sb.setSpan(new StyleSpan(Typeface.ITALIC),startTwo,endTwo , 0);
        sb.setSpan(new RelativeSizeSpan(0.8f), startTwo, endTwo, 0);
    
        textView.setText(sb);
    }
    

    enter image description here