gpt4 book ai didi

android - 在 Android 小部件中删除文本的子字符串

转载 作者:太空狗 更新时间:2023-10-29 16:13:48 27 4
gpt4 key购买 nike

我的 android 小部件中有一个 TextView ,我只需要删除某些文本行。我在另一个 SO 问题中发现了这个以删除小部件中的文本:

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

// strike through text, this strikes through all text
views.setInt(R.id.appwidget_text, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

问题是这会贯穿 TextView 中的所有文本。我怎样才能只删除 TextView 文本的一部分?

最佳答案

使用 SpannableStringBuilderStrikethroughSpan

例如,要获得以下效果,请参见下面的代码 fragment : enter image description here


String firstWord = "Hello";
String secondWord = "World!";

TextView tvHelloWorld = (TextView)findViewById(R.id.tvHelloWorld);

// Create a span that will make the text red
ForegroundColorSpan redForegroundColorSpan = new ForegroundColorSpan(
getResources().getColor(android.R.color.holo_red_dark));

// Use a SpannableStringBuilder so that both the text and the spans are mutable
SpannableStringBuilder ssb = new SpannableStringBuilder(firstWord);

// Apply the color span
ssb.setSpan(
redForegroundColorSpan, // the span to add
0, // the start of the span (inclusive)
ssb.length(), // the end of the span (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the SpannableStringBuilder
// SPAN_EXCLUSIVE_EXCLUSIVE means to not extend the span when additional
// text is added in later

// Add a blank space
ssb.append(" ");

// Create a span that will strikethrough the text
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();

// Add the secondWord and apply the strikethrough span to only the second word
ssb.append(secondWord);
ssb.setSpan(
strikethroughSpan,
ssb.length() - secondWord.length(),
ssb.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the TextView text and denote that it is Editable
// since it's a SpannableStringBuilder
tvHelloWorld.setText(ssb, TextView.BufferType.EDITABLE);

更多炫酷效果 here

关于android - 在 Android 小部件中删除文本的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com