Search code examples
androidxmlandroid-layouttextviewandroid-linearlayout

TextViews alignment with dynamic content


Current view: enter image description here

This is the expected result: enter image description here

The thing is that the red text is dynamic I don't know the length until run-time.

Currently I have a LinearLayout and in it I have two TextViews one for the red text and another for the clickable link. I have managed to display the link below the red text with LinearLayout android:orientation=vertical.

If I set it to android:orientation=horizontal the link goes to the far right not next to the content of the red text.

My Current XML:

<LinearLayout
        android:paddingLeft="16dp"
        android:paddingRight="@dimen/card_container_padding"
        android:paddingTop="@dimen/card_container_padding"
        android:paddingBottom="@dimen/card_container_padding"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/cms_message_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="@dimen/body_text_size"
            android:textStyle="bold"
            android:textAlignment="center"
            android:layout_weight="0"
            android:text=""/>

        <TextView
            android:id="@+id/cms_message_modal_link"
            android:layout_marginLeft="@dimen/account_home_line_margin_top"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/lightBlue"
            android:layout_weight="1"
            android:textAlignment="textEnd"
            android:layout_gravity="end"
            android:textStyle="bold"
            android:textSize="@dimen/body_text_size"
            android:text="More Info"/>

    </LinearLayout>

Should I use a different layout or is there an attribute that can help me?


Solution

  • While Xan's answer isn't wrong for display purposes it doesn't allow only the underline portion to be clicked. I suggest using:

    TextView textView = (TextView) findViewById(R.id.cms_message_content);
    SpannableString ss = new SpannableString("Here is some non linked text, but this is linked");
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Hey you clicked me", Toast.LENGTH_SHORT).show();
        }
    };
    int indexOfComma = ss.toString().indexOf(","); /* just for this case, im coloring after the comma */
    ss.setSpan(clickableSpan, indexOfComma + 1, ss.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(ss);
    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setLinkTextColor(Color.BLUE);