ImageSpan的使用
16lz
2021-01-24
编辑框中加图片,以前一直以为很复杂,后来发现android有些类已经很好的实现了这些功能.
代码如下:
[java] view plain copy
- mSubjectDetailView = (TextView) findViewById(R.id.subject_detail);
- CharSequence text = "如图所示★,dsfdsfdddd,如果fdsfs★东东";
- SpannableStringBuilder builder = new SpannableStringBuilder(text);
- String rexgString = "★";
- Pattern pattern = Pattern.compile(rexgString);
- Matcher matcher = pattern.matcher(text);
- while (matcher.find()) {
- builder.setSpan(
- new ImageSpan(this, R.drawable.ic_launcher), matcher.start(), matcher
- .end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- mSubjectDetailView.setText(builder);
[html] view plain copy
- <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=".MainActivity" >
- <TextView
- android:id="@+id/my_title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/hello_world" />
- <TextView
- android:id="@+id/subject_detail"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:minHeight="50dp"
- android:gravity="center_vertical"
- android:text="subject"
- android:textColor="@android:color/primary_text_light_nodisable"
- android:background="@android:color/white"
- android:textSize="25sp" />
- RelativeLayout>
效果:
android 图文结合,使用SpannableString和ImageSpan类
Drawable drawable = getResources().getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
//需要处理的文本,[smile]是需要被替代的文本
SpannableString spannable = new SpannableString(getText().toString()+"[smile]");
//要让图片替代指定的文字就要用ImageSpan
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
//开始替换,注意第2和第3个参数表示从哪里开始替换到哪里替换结束(start和end)
//最后一个参数类似数学中的集合,[5,12)表示从5到12,包括5但不包括12
spannable.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
setText(spannable);
更多相关文章
- Android(安卓)屏幕常亮
- Android自动化测试MonkeyRunner
- Android(安卓)Activity界面切换添加动画特效
- Android之SharedPreferences对参数数据的存取
- android 获取Service(服务)的运行状态
- 【Appium + Python3】之安卓8.1,使用xpath定位不到元素
- Android(安卓)setTextColor 不生效
- Android二进制文件转码到Base64并通过Post进行提交
- Android第十二课 jni函数的静态绑定