代码如下:
package gyf.google;
import android.R.string;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Html.ImageGetter;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class test1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dit_text_test1);
final EditText eText=(EditText)findViewById(R.id.test1_editText1);
ImageGetter imageGetter = new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id = Integer.parseInt(source);
//根据id从资源文件中获取图片对象
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
};
SpannableStringBuilder sBuilder=new SpannableStringBuilder(eText.getText().toString());
Drawable drawable=getResources().getDrawable(R.drawable.hungry_1);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
sBuilder.setSpan(imageSpan, eText.getText().toString().length()-6,eText.getText().toString().length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
eText.setText(sBuilder);
String ssString="gyflyx";
ssString=ssString+eText.getText().toString();
eText.setText(ssString);
sBuilder=new SpannableStringBuilder(eText.getText().toString());
drawable=getResources().getDrawable(R.drawable.bad_smelly_1);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
sBuilder.setSpan(imageSpan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
eText.setText(sBuilder);
eText.append(Html.fromHtml("<img src='"+R.drawable.byebye+"'/>", imageGetter, null));
//获取光标位置并插入
Button button=(Button)findViewById(R.id.test1_button1);
final EditText eText2=(EditText)findViewById(R.id.test1_editText2);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SpannableStringBuilder sBuilder=new SpannableStringBuilder(eText2.getText().toString());
Drawable drawable=getResources().getDrawable(R.drawable.hungry_1);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
sBuilder.setSpan(imageSpan,0,eText2.getText().toString().length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
//eText.setText(sBuilder);
int nowLocation=eText.getSelectionStart();
eText.getText().insert(nowLocation, sBuilder);
}
});
}
}