how to set underline and color to partly text at one time on TextView?

我的梦境 提交于 2020-01-06 19:46:52

问题


I have a string in my EditText, and threre is an URL link in this string.

So I want to set this link have underline and blue color as common sense.

Now I can add underline by using "u" tag and Html.fromHtml(), but can't set color, this is my code:

String text = "some string <u><font color=\"#0000FF\">some link</font></u>";
editText.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);

Can someone help me? Thanks!


回答1:


I tried this on an emulator running Android 2.2, another emulator running Android 3.2, and on a phone running Android 4.0.3, and the code you posted works fine on all three platforms (the text "some link" is both underlined and in blue).

Here's the layout I used:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:hint="@string/hello_world" >

    <requestFocus />
</EditText>

Here's the complete Activity code:

package com.example.andtest01;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    EditText editText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText1);

        String text = "some string <u><font color=\"#0000FF\">some link</font></u>";
        editText.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
    }

}



来源:https://stackoverflow.com/questions/12284264/how-to-set-underline-and-color-to-partly-text-at-one-time-on-textview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!