是因为文本视图(TextView)的颜色属性是只读的,无法直接设置。但是可以通过其他方式来改变文本视图的颜色,下面是几种常用的方法:
TextView textView = findViewById(R.id.text_view);
SpannableString spannableString = new SpannableString("Hello, World!");
ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.RED);
spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
TextView textView = findViewById(R.id.text_view);
String htmlString = "<font color='#FF0000'>Hello, World!</font>";
Spanned spanned = Html.fromHtml(htmlString);
textView.setText(spanned);
public class CustomTextView extends TextView {
private Paint paint;
public CustomTextView(Context context) {
super(context);
init();
}
public CustomTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(getText().toString(), 0, getText().length(), 0, getTextSize(), paint);
}
}
在布局文件中使用自定义的文本视图:
<com.example.app.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
以上是几种常用的方法来改变文本视图的颜色。根据具体的需求和场景选择合适的方法。腾讯云相关产品和产品介绍链接地址请参考腾讯云官方网站。
领取专属 10元无门槛券
手把手带您无忧上云