在Android中设置文本视图范围的颜色

在Android中设置文本视图范围的颜色,android,text,formatting,textview,Android,Text,Formatting,Textview,是否可以在TextView中设置文本宽度的颜色 我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图: (来源:)设置文本视图的文本span可启用,并为文本定义前景颜色span TextView textView = (TextView)findViewById(R.id.mytextview01); Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I kno

是否可以在TextView中设置文本宽度的颜色

我想做一些类似于Twitter应用程序的事情,其中一部分文本是蓝色的。见下图:



(来源:)

设置
文本视图的文本span可启用,并为文本定义
前景颜色span

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

另一个答案非常类似,但不需要设置
TextView
的文本两次

TextView TV = (TextView)findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);

这里有一个小的帮助功能。当你有多种语言的时候,非常适合

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

有一个工厂可以创建Spanable,并避免使用cast,如下所示:

Spannable span = Spannable.Factory.getInstance().newSpannable("text");
<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

在某些情况下,可以使用的另一种方法是在采用可扩展性的视图的属性中设置链接颜色

例如,如果您的Spannable将在TextView中使用,您可以在XML中设置链接颜色,如下所示:

Spannable span = Spannable.Factory.getInstance().newSpannable("text");
<TextView
    android:id="@+id/myTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorLink="@color/your_color"
</TextView>

如果需要更多控制,可能需要检查
TextPaint
类。以下是如何使用它:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

通过传递字符串和颜色设置文本上的颜色

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}
获取彩色字符串:

TextView txtView = (TextView)findViewById(R.id.txtView);
String name = getColoredSpanned("Hiren", "#800000");
txtView.setText(Html.fromHtml(name));
在文本视图上设置文本:

TextView txtView = (TextView)findViewById(R.id.txtView);
String name = getColoredSpanned("Hiren", "#800000");
txtView.setText(Html.fromHtml(name));

完成

当我试图理解一个新概念时,我总是发现直观的例子很有帮助

背景色

前景色

组合

进一步研究
  • 在您的布局中创建文本视图
  • 将此代码粘贴到您的MainActivity中

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    
  • 输出:


    只需添加到已接受的答案中,因为所有答案似乎都只是在讨论:如果我想要的颜色是在
    res/values/colors.xml
    中定义的,该怎么办

    例如,考虑在<代码>颜色中定义。XML<代码>:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="md_blue_500">#2196F3</color>
    </resources>
    
    变成:

    wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    我发现:


    这里有一个Kotlin扩展函数

        fun TextView.setColouredSpan(word: String, color: Int) {
            val spannableString = SpannableString(text)
            val start = text.indexOf(word)
            val end = text.indexOf(word) + word.length
            try {
                spannableString.setSpan(ForegroundColorSpan(color), start, end,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                text = spannableString
            } catch (e: IndexOutOfBoundsException) {
             println("'$word' was not not found in TextView text")
        }
    }
    
    在将文本设置为文本视图后使用它,如下所示

    private val blueberry by lazy { getColor(R.color.blueberry) }
    
    textViewTip.setColouredSpan("Warning", blueberry)
    

    下面对我来说非常合适

        tvPrivacyPolicy = (TextView) findViewById(R.id.tvPrivacyPolicy);
        String originalText = (String)tvPrivacyPolicy.getText();
        int startPosition = 15;
        int endPosition = 31;
    
        SpannableString spannableStr = new SpannableString(originalText);
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableStr.setSpan(underlineSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(Color.BLUE);
        spannableStr.setSpan(backgroundColorSpan, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        StyleSpan styleSpanItalic  = new StyleSpan(Typeface.BOLD);
    
        spannableStr.setSpan(styleSpanItalic, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    
        tvPrivacyPolicy.setText(spannableStr);
    
    以上代码的输出


    这里的一些答案不是最新的。因为,您将(在大多数情况下)在链接上添加自定义clic操作

    此外,正如文档帮助所提供的,您的跨字符串链接颜色将具有默认颜色。 “默认链接颜色是主题的强调色,如果在主题中定义了此属性,则为android:textColorLink”

    以下是安全操作的方法

     private class CustomClickableSpan extends ClickableSpan {
    
        private int color = -1;
    
        public CustomClickableSpan(){
            super();
            if(getContext() != null) {
                color = ContextCompat.getColor(getContext(), R.color.colorPrimaryDark);
            }
        }
    
        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            ds.setColor(color != -1 ? color : ds.linkColor);
            ds.setUnderlineText(true);
        }
    
        @Override
        public void onClick(@NonNull View widget) {
        }
    }
    
    然后使用它

       String text = "my text with action";
        hideText= new SpannableString(text);
        hideText.setSpan(new CustomClickableSpan(){
    
            @Override
            public void onClick(@NonNull View widget) {
                // your action here !
            }
    
        }, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        yourtextview.setText(hideText);
        // don't forget this ! or this will not work !
        yourtextview.setMovementMethod(LinkMovementMethod.getInstance());
    

    希望这将有力地帮助

    从开发人员文档中,要更改可打印文件的颜色和大小,请执行以下操作:

    1-创建一个类:

        class RelativeSizeColorSpan(size: Float,@ColorInt private val color: Int): RelativeSizeSpan(size) {
    
        override fun updateDrawState(textPaint: TextPaint?) {
            super.updateDrawState(textPaint)
            textPaint?.color = color
        } 
    }
    
    2使用该类创建您的Spanable:

        val spannable = SpannableStringBuilder(titleNames)
    spannable.setSpan(
        RelativeSizeColorSpan(1.5f, Color.CYAN), // Increase size by 50%
        titleNames.length - microbe.name.length, // start
        titleNames.length, // end
        Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    )
    

    使用kotlin ktx,您可以轻松实现它

            bindView?.oneTimePasswordTitle?.text = buildSpannedString {
            append("One Time Password ")
            inSpans(
                ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
            ){
                append(" (As Registered Email)")
            }
    
        }
    


    谢谢如果不先将文本分配给TextView,是否可以执行此操作?我没有很好地解释自己。让我重新措辞。前三行是必要的吗?你不能直接从字符串创建Spanable对象吗?不,你必须将TextView的文本存储到一个缓冲区Spanable以更改前景颜色。我想用同样的颜色,加上我希望所有内容都是粗体的,除了彩色部分,那部分我想是斜体,我该怎么做?如何设置跨度中的点击?您能说明如何使用SpannableFactory吗?“文本”应该是什么样子?在SpannableFactory创建了Spannable之后,如何使用它?但是我如何更改多个单词的颜色?我所有的文本不是一个span?@mostafahashim通过重复第3行wordtoSpan.setSpan(新的ForegroundColorSpan(color.RED),50,80,Spannable.span_EXCLUSIVE_EXCLUSIVE)来创建多个span;Kotlin+Spanable字符串解决方案看起来像是Android 6.0 Marshmallow(API 23)上不推荐使用此getColor(int id)单击Listener的好答案。你不喜欢Hasina,非常感谢你让我开心:*应该是Kotlin实现的最佳答案。我如何在这里添加曲线背景??@GkMohammadEmon,这听起来像是定制绘画,而不是简单的背景色。看看贝塞尔曲线。你有关于它的好的参考资料或资源吗?我需要为我的通知操作按钮添加曲线背景。谢谢你的帮助response@GkMohammadEmon对不起,我没有。自从我开始使用Flutter以来,我已经有一段时间没有在Android上进行自定义绘制了。
            bindView?.oneTimePasswordTitle?.text = buildSpannedString {
            append("One Time Password ")
            inSpans(
                ForegroundColorSpan(ContextCompat.getColor(bindView?.oneTimePasswordTitle?.context!!,R.color.colorPrimaryText))
            ){
                append(" (As Registered Email)")
            }
    
        }