Android TextView autoLink 改变颜色,去掉link下划线

本文介绍了如何在Android中修改TextView的自动链接颜色,以及如何通过自定义UnderlineSpan子类来去除链接的下划线。在XML中使用textColorLink属性改变链接颜色,并展示了设置文本及实现效果的方法。需要注意的是,这种方法在Data Binding的双向绑定中可能无效,需用setText方式设置文本。

更改颜色:xml中使用textColorLink属性

删除下划线:自定义一个继承UnderlineSpan 的子类,重写updateDrawState方法在其中处理

 

xml界面代码: 

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="https://www.baidu.com/"
        android:autoLink="web"
        android:textColorLink="@color/colorRed"
        android:textIsSelectable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 Activity界面代码:

public class MainActivity extends AppCompatActivity {

    TextView txt_link ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt_link = findViewById(R.id.txt_link);
        NoUnderlineSpan mNoUnderlineSpan = new NoUnderlineSpan();
        if (txt_link.getText() instanceof Spannable) {
            Spannable s = (Spannable) txt_link.getText();
            s.setSpan(mNoUnderlineSpan, 0, s.length(), Spanned.SPAN_MARK_MARK);
        }
    }


    public class NoUnderlineSpan extends UnderlineSpan {

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);
        }
    }
}

效果:

ps: 这个写法在databinding的双向绑定无效,文字内容要用setText的方式设置

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值