关闭

TextView和SpannableString实现图文混排的效果

105人阅读 评论(0) 收藏 举报
分类:

使用SpannableString和TextView可以实现一个图文混排的效果

实现代码:

Activity_Main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.studyTextView.MainActivity" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</RelativeLayout>

MainActivity.java

package com.studyTextView;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView textView1;
	private SpannableString msb;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView1 = (TextView) findViewById(R.id.textView);
		 msb = new SpannableString("\b玫瑰玫瑰");
		 textImage(textView1,msb);
		 
	}
	
	public void textImage(TextView mtextView,SpannableString msb){  
		Drawable drawable = getResources().getDrawable(R.drawable.daohang); //daohang为drawable下图片名
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		
		msb.setSpan(new ImageSpan(drawable), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		mtextView.setText(msb);
		mtextView.setMovementMethod(LinkMovementMethod.getInstance());
	}

}

drawable.getIntrinsicWidth()和<span style="font-family: Arial, Helvetica, sans-serif;">drawable.getIntrinsicHeight()获取屏幕的大小</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size: 14px;">运行结果:</span>
</span>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1175次
    • 积分:66
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类