有勇气的牛排博客

安卓 setText()使用 嵌套html代码

有勇气的牛排 1105 安卓 2021-10-17 01:04:48

基础用法

package com.example.study; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView1 = (TextView) findViewById(R.id.test); // 基础用法 textView1.setText("666"); textView1.setTextSize(20); } }

嵌套html

索要使用的html代码:

<span style="color: red;">2</span>

2

安卓实现:

package com.example.study; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView1 = (TextView) findViewById(R.id.test); // html代码 String data = "<span style=\"color: red;\">2</span>元"; // 使用 Html.fromHtml()函数 textView1.setText(Html.fromHtml(data)); textView1.setTextSize(20); } }

留言

专栏
文章
加入群聊