textview.settextcolor和textview.setbackground
时间: 2024-04-27 09:22:08 浏览: 13
textview.settextcolor是用来设置TextView中文字的颜色,我们可以传入一个颜色值或者一个ColorStateList对象来设置不同状态下文字的颜色。例如:
```
textView.setTextColor(Color.RED); // 设置文字颜色为红色
```
而textview.setbackground是用来设置TextView的背景颜色或者背景图片的,我们可以传入一个颜色值或者一个Drawable对象来设置。例如:
```
textView.setBackgroundResource(R.color.background_color); // 设置背景颜色为颜色资源文件中定义的颜色
```
相关问题
android12使用TextView.setbackground()怎么给TextView添加边框
要给TextView添加边框,可以使用TextView的setBackground()方法和ShapeDrawable来创建一个具有边框的Drawable对象,然后将其设置为TextView的背景。以下是示例代码:
```
// 创建一个ShapeDrawable对象
ShapeDrawable border = new ShapeDrawable();
border.setShape(new RectShape());
border.getPaint().setColor(Color.RED);
border.getPaint().setStrokeWidth(2f);
border.getPaint().setStyle(Paint.Style.STROKE);
// 获取TextView对象
TextView textView = findViewById(R.id.text_view);
// 将ShapeDrawable对象设置为TextView的背景
textView.setBackground(border);
```
在上面的示例中,我们创建了一个ShapeDrawable对象,并将其设置为具有红色边框和2像素宽度的矩形形状。然后,我们获取了TextView对象,并使用setBackground()方法将ShapeDrawable对象设置为其背景。这将在TextView周围创建一个红色的边框。您可以根据需要调整颜色,宽度和形状来创建自定义边框。
textView.setText文本改字体颜色
您可以使用SpannableString和ForegroundColorSpan类来实现这个功能。下面是一个示例代码:
```java
TextView textView = findViewById(R.id.textView);
String text = "这是需要改变颜色的文本";
SpannableString spannableString = new SpannableString(text);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED); // 设置颜色为红色
spannableString.setSpan(colorSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
```
在这个示例中,我们首先获取了一个TextView实例和需要改变颜色的文本。然后,我们创建了一个SpannableString对象,并设置颜色为红色。接着,我们使用setSpan方法将ForegroundColorSpan对象应用于SpannableString对象,并将其设置为TextView的文本。
如果您需要将多个文本片段的字体颜色改变,可以多次调用setSpan方法。例如:
```java
TextView textView = findViewById(R.id.textView);
String text = "这是需要改变颜色的文本";
SpannableString spannableString = new SpannableString(text);
ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(Color.RED); // 设置第一个片段的颜色为红色
ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(Color.BLUE); // 设置第二个片段的颜色为蓝色
spannableString.setSpan(colorSpan1, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 第一个片段的范围是0-4
spannableString.setSpan(colorSpan2, 5, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // 第二个片段的范围是5到文本末尾
textView.setText(spannableString);
```
在这个示例中,我们将文本分为两个片段,分别将它们的颜色设置为红色和蓝色,并使用setSpan方法将ForegroundColorSpan对象应用于SpannableString对象,并将其设置为TextView的文本。