给EditText中的图片加监听

时间:2023-03-08 20:47:30
package com.example.helloword;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
EditText txtEdit;
ImageSpan imageSpan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEdit = (EditText) findViewById(R.id.et_button);
txtEdit.setOnClickListener(textListener); imageSpan = new ImageSpan(this, R.drawable.ic_launcher);
SpannableString ss = new SpannableString("photo");
ss.setSpan(imageSpan, 0, "photo".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Editable editable = txtEdit.getEditableText();
int selectedIndex = txtEdit.getSelectionStart();
ss.getSpans(0, ss.length(), ImageSpan.class);
if (selectedIndex < 0)
editable.append(ss);
else
editable.insert(selectedIndex, ss);
} private OnClickListener textListener = new OnClickListener()
{
@Override
public void onClick(View v)
{ //关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtEdit.getWindowToken(), 0);
Spanned s = txtEdit.getText();
ImageSpan[] imageSpans = s.getSpans(0, s.length(), ImageSpan.class);
int selectionStart = txtEdit.getSelectionStart();
for (ImageSpan span : imageSpans)
{
int start = s.getSpanStart(span);
int end = s.getSpanEnd(span);
if (selectionStart >= start && selectionStart < end)//找到图片
{
Bitmap bitmap = ((BitmapDrawable) span.getDrawable()).getBitmap();
viewPicture(bitmap);
return;
}
}
//打开软键盘
imm.showSoftInput(txtEdit, 0);
}
}; private void viewPicture(Bitmap bitmap)
{
System.out.println("*******************************");
/* if (bitmap == null)
return;
//将由图片生成Uri
Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent); */
}
}