如何在TextView中以粗体和多色显示文本

我的要求是在TextView中以彩虹色文本和Bold显示多色文本,如何实现这一点。我需要使用java代码动态显示它们。

TextView text=new TextView(context); text.setText(status); text.setBackgroundResource(R.drawable.grd_btn); text.setGravity(Gravity.CENTER); text.setPadding(2, 0, 2, 0); text.setTypeface(font2,Typeface.BOLD); text.setTextColor(Color.WHITE); 

嘿抱歉我的朋友耽误了。 不得不解决你的问题,这需要一段时间。 首先是输出,

在此处输入图像描述

因此,假设上面显示的是您需要的输出,这里是代码。

xml文件

  

res文件(比如strings.xml)

 #9400D3 #4B0082 #0000FF #00FF00 #FFFF00 #FF7F00 #FF0000 

你的java文件

  TextView textView = (TextView)findViewById(R.id.textView1); Shader textShader=new LinearGradient(0, 0, 0, 20, new int[]{getResources().getColor(R.color.violet),getResources().getColor(R.color.indigo), getResources().getColor(R.color.blue), getResources().getColor(R.color.green), getResources().getColor(R.color.yellow), getResources().getColor(R.color.orange), getResources().getColor(R.color.red)}, new float[]{0,0.2f,0.4f,0.6f,0.8f,0.9f,1}, TileMode.CLAMP); textView.getPaint().setShader(textShader); textView.setTextSize(20); 

而已。 对于你的大胆风格,请按照我之前的答案的以下链接,

https://stackoverflow.com/a/5169604/603744

  String text = "This is red. This is blue."; textView.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE); textView.setTypeface(null,Typeface.BOLD); 

这对我来说最简单

所有积分: https : //gist.github.com/ishitcno1/0c8bcb8ad72cb0879acb

 public class RainbowTextView extends TextView { protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); int[] rainbow = getRainbowColors(); Shader shader = new LinearGradient(0, 0, 0, w, rainbow, null, Shader.TileMode.MIRROR); Matrix matrix = new Matrix(); matrix.setRotate(90); shader.setLocalMatrix(matrix); getPaint().setShader(shader); } private int[] getRainbowColors() { return new int[] { getResources().getColor(R.color.rainbow_red), getResources().getColor(R.color.rainbow_yellow), getResources().getColor(R.color.rainbow_green), getResources().getColor(R.color.rainbow_blue), getResources().getColor(R.color.rainbow_purple) }; } }