AndroidTextView实现图文混合编排的方法

本文实例为大家分享了Android TextView图文混合编排的具体代码,供大家参考,具体内容如下

我们提供的服务有:成都做网站、网站制作、成都外贸网站建设、微信公众号开发、网站优化、网站认证、清水河ssl等。为近千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的清水河网站制作公司

实现技术细节不难,两个要点:

1、html代码的混合编写。
2、重写ImageGetter。

例如:

布局:

<?xml version="1.0" encoding="utf-8"?>


 

 

 

 


 Java代码:

package zhangphil.app;

import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 TextView text1 = (TextView) findViewById(R.id.text1);
 TextView text2 = (TextView) findViewById(R.id.text2);
 TextView text3 = (TextView) findViewById(R.id.text3);
 TextView text4 = (TextView) findViewById(R.id.text4);

 String s = "zhang phil @ csdn Android TextView图文混编";

 CharSequence cs1 = Html.fromHtml(stringMixWithImage1(s), imgageGetter, null);
 text1.setText(cs1);

 CharSequence cs2 = Html.fromHtml(stringMixWithImage2(s), imgageGetter, null);
 text2.setText(cs2);

 CharSequence cs3 = Html.fromHtml(stringMixWithImage3(s), imgageGetter, null);
 text3.setText(cs3);

 CharSequence cs4 = Html.fromHtml(stringMixWithImage4(s), imgageGetter, null);
 text4.setText(cs4);
 }

 private String stringMixWithImage1(String string) {
 return string + "1 " + "" + " " + "" + " " + "" + " ";
 }

 private String stringMixWithImage2(String string) {
 return "2 " + "" + " " + "" + " " + "" + " " + string;
 }

 private String stringMixWithImage3(String string) {
 return string + "3 " + "" + " " + "" + " " + "" + " ";
 }

 private String stringMixWithImage4(String string) {
 return "4 " + "" + " " + "" + " " + "" + " " + string;
 }

 private Html.ImageGetter imgageGetter = new Html.ImageGetter() {
 @Override
 public Drawable getDrawable(String source) {
  int id = Integer.parseInt(source);
  Drawable d = ContextCompat.getDrawable(getApplicationContext(), id);
  d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
  return d;
 }
 };
}

代码运行结果:

Android TextView实现图文混合编排的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


新闻标题:AndroidTextView实现图文混合编排的方法
分享网址:http://myzitong.com/article/ghgeep.html