EditText中插入图片

main.xml如下:

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dip"
        android:textSize="18sp"
        android:text="测试:往EditText中插入图片" />
    
    <EditText 
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="30dip"
        android:layout_height="180dip"
        android:layout_marginTop="50dip"
        android:hint="插入表情"
        />
    
     <Button 
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="30dip"
        android:layout_height="80dip"
        android:layout_marginTop="250dip"
        android:hint="插入表情"
        />

</RelativeLayout>


MainActivity如下:

package com.cn;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.graphics.BitmapFactory;
/**
 * Demo描述:
 * 往EditText中插入图片
 */
public class MainActivity extends Activity {
	private EditText mEditText;
	private Button mButton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}
	private void init(){
		mEditText=(EditText) findViewById(R.id.editText);
		mButton=(Button) findViewById(R.id.button);
		mButton.setOnClickListener(new ClickListenerImpl());
	}

	private class ClickListenerImpl implements OnClickListener {
		@Override
		public void onClick(View v) {
			ImageSpan imageSpan = new ImageSpan(MainActivity.this,
			BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher));
			SpannableString spannableString = new SpannableString("test");
			spannableString.setSpan(imageSpan, 0, spannableString.length(),SpannableString.SPAN_MARK_MARK);
			mEditText.append(spannableString);
		}

	}

}


 

你可能感兴趣的:(EditText中插入图片)