欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-01 09:15:00
...

更改颜色: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);
        }
    }
}

效果:

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

相关标签: android