5分钟
TextView玩转HTML
如题,除了显示普通文本外,TextView还预定义了一些类似于HTML的标签,通过这些标签,我们可以使 TextView显示不同的字体颜色,大小,字体,甚至是显示图片,或者链接等!我们只要使用HTML中的一些 标签,加上android.text.HTML类的支持,即可完成上述功能!
PS:当然,并不是支持所有的标签,常用的有下述这些:
- <font>:设置颜色和字体。
- <big>:设置字体大号
- <small>:设置字体小号
- <i><b>:斜体粗体
- <a>:连接网址
- <img>:图片
如果直接setText的话是没作用的,我们需要调用Html.fromHtml()方法将字符串转换为CharSequence接口, 然后再进行设置,如果我们需要相应设置,需要为TextView进行设置,调用下述方法: Java setMovementMethod(LinkMovementMethod.getInstance())
嗯,接着我们写代码来试试:
1)测试文本与超链接标签
package jay.com.example.textviewdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t1 = (TextView)findViewById(R.id.txtOne);
String s1 = "<font color='blue'><b>百度一下,你就知道~:</b></font><br>";
s1 += "<a href = 'http://www.baidu.com'>百度</a>";
t1.setText(Html.fromHtml(s1));
t1.setMovementMethod(LinkMovementMethod.getInstance());
}
}
运行效果图:
恩呢,测试完毕~
2)测试src标签,插入图片:
看下运行效果图:
接下来看下实现代码,实现代码看上去有点复杂,用到了反射(对了,别忘了在drawable目录下放一个icon的图片哦!):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t1 = (TextView) findViewById(R.id.txtOne);
String s1 = "图片:<img src = 'icon'/><br>";
t1.setText(Html.fromHtml(s1, new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable draw = null;
try {
Field field = R.drawable.class.getField(source);
int resourceId = Integer.parseInt(field.get(null).toString());
draw = getResources().getDrawable(resourceId);
draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
} catch (Exception e) {
e.printStackTrace();
}
return draw;
}
}, null));
}
}
嘿嘿,你也可以自己试试,比如为图片加上超链接,点击图片跳转这样~
学员评价