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

2 java android textview android-layout

我的要求是在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);
Run Code Online (Sandbox Code Playgroud)

And*_*lva 9

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

在此输入图像描述

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

xml文件

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world"/>
Run Code Online (Sandbox Code Playgroud)

res文件(比如strings.xml)

<color  name="violet">#9400D3</color>
<color  name="indigo">#4B0082</color>
<color  name="blue">#0000FF</color>
<color  name="green">#00FF00</color>
<color  name="yellow">#FFFF00</color>
<color  name="orange">#FF7F00</color>
<color  name="red">#FF0000</color>
Run Code Online (Sandbox Code Playgroud)

你的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);
Run Code Online (Sandbox Code Playgroud)

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

/sf/answers/361872311/

  • 你太棒了 (3认同)