Android笔记:TextView和编辑框中添加图片,ImageSpan,SpannableStringBuilder用法
在TextView或者编辑框EditText中添加图片的方法,代码如下:
importjava.util.regex.Matcher;importjava.util.regex.Pattern;importandroid.os.Bundle;importandroid.app.Activity;importandroid.text.Spannable;importandroid.text.SpannableStringBuilder;importandroid.text.style.ImageSpan;importandroid.widget.EditText;importandroid.widget.TextView;publicclassMainActivityextendsActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextViewtv=(TextView)findViewById(R.id.tv);Stringstr="sdfasd★fasljeojg★fadfalsdkjf★asjdkfalsdj★foawpjfsajfadsjfladjfals";SpannableStringBuilderbuilder=newSpannableStringBuilder(str);Stringflag="★";Patternpattern=Pattern.compile(flag);Matchermatcher=pattern.matcher(str);while(matcher.find()){builder.setSpan(newImageSpan(this,R.drawable.ic_launcher),matcher.start(),matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);}tv.setText(builder);EditTexted=(EditText)findViewById(R.id.editText1);ed.setText(builder);}}
布局文件代码如下:
<RelativeLayoutxmlns: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"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity"><TextViewandroid:id="@+id/tv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world"/><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@+id/tv"android:layout_marginTop="63dp"android:ems="10"><requestFocus/></EditText></RelativeLayout>
效果图:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。