Monday, June 25, 2012

Android ImageSpan Example



res/layout/main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<EditText 
        android:id="@+id/editText1"
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:minLines="6"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
<TextView 
        android:id="@+id/txtview"
        android:layout_width="fill_parent"
        android:textSize="25.0dp"
        android:gravity="center"
        android:layout_height="wrap_content"
        android:text="ImageSpan" />
</LinearLayout>


ImageSpanActivity.java:
public class ImageSpanActivity extends Activity {
 private EditText ettxt;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ettxt = (EditText) this.findViewById(R.id.editText1);
        ettxt.setText("HelloWorld");
        
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
  drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
    drawable.getIntrinsicHeight());
  SpannableString spannable = new SpannableString(getText()
    .toString() + "[smile]");
  ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
  spannable.setSpan(span, getText().length(),
    getText().length() + "[smile]".length(),
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
  setText(spannable);
    }
 private Editable getText() {
  return ettxt.getText();
 }

 private void setText(SpannableString spannalbe) {
  ettxt.setText(spannalbe);

 }
}


Download Source Code: AndroidImageSpan









1 comments:

ravindra said...

how to set image to middle of text like i have text "use promo code 8944RD" I want to set drawable to background of 8944RD. Is there any way

Post a Comment

 
Powered by Blogger