package com.imo; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; import android.text.Html.ImageGetter; import android.text.style.ImageSpan; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class Android_demoActivity extends Activity { private TextView text; private EditText edit; private ImageGetter imageGetter = new ImageGetter() { public Drawable getDrawable(String source) { int id = Integer.parseInt(source); Drawable d = getResources().getDrawable(id); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); edit = (EditText) findViewById(R.id.edit); text = (TextView) findViewById(R.id.text); insertPic2(); text.setText(edit.getText()); insertPic1(); } public void click(View view) { System.out.println(edit.getText()); } /** * 第一种插入图片方式 */ private void insertPic1() { SpannableString ss = new SpannableString("pic"); Drawable d = getResources().getDrawable(R.drawable.icon); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM); ss.setSpan(span, 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); edit.append(ss); } /** * 第二种插入图片方式 */ private void insertPic2() { edit.append(Html.fromHtml("<img src='" + R.drawable.icon + "'/>", imageGetter, null)); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/edit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="sb" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击" android:onClick="click" /> </LinearLayout>