酷代码 AI
菜单

在android开发中,spannablestring的使用

SpannableString是在Android中用于创建可以被高亮、下划线、删除线等样式标记的字符串的类。它可以在字符串中添加Span(样式标记)。 以下是一个简单的例子,展示了如何使用SpannableString: ```java import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SpannableString spannableString = new SpannableString("Hello, World!"); // 创建一个ForegroundColorSpan对象,设置文本颜色为红色 ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.RED); // 将ForegroundColorSpan添加到spannableString中,从第6个字符开始,持续到字符串结束 spannableString.setSpan(foregroundColorSpan, 5, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 将spannableString设置到TextView中 TextView textView = findViewById(R.id.textView); textView.setText(spannableString); } } ``` 在这个例子中,我们创建了一个SpannableString对象,然后创建了一个ForegroundColorSpan对象来设置文本颜色。然后,我们将ForegroundColorSpan添加到spannableString中,从第6个字符开始,持续到字符串结束。我们将spannableString设置到TextView中。 这只是一个基本的例子,SpannableString可以包含多种不同的Span,包括ForegroundColorSpan、UnderlineSpan、StrikethroughSpan等等。 [2023-11-07 22:39:04 | AI写代码神器 | 327点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多