我正在尝试在Android上的EditText小部件中插入内嵌文本的图像。当我点击“Take”按钮时,我在对话框中选择“Choose From Gallery”。当我从Android图像库中选择一个图像时,会弹出“字符串”Toast消息,但图像不会插入与文本内联的EditText中。这是我正在使用的源代码:
BasicService.showDocument()
这是XML布局代码:
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import com.example.kh9275.stuff.R;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText et;
Button keyboard, camera, take;
LinearLayout cameraLayout;
GridLayout grid;
SharedPreferences prefs;
SharedPreferences.Editor editor;
static int index;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.et);
keyboard = (Button) findViewById(R.id.keyboard);
camera = (Button) findViewById(R.id.camera);
take = (Button) findViewById(R.id.take);
cameraLayout = (LinearLayout) findViewById(R.id.cameraLayout);
cameraLayout.setVisibility(View.GONE);
grid = (GridLayout) findViewById(R.id.grid);
prefs = getSharedPreferences("stuff", Context.MODE_PRIVATE);
index = prefs.getInt("index", 1);
Toast.makeText(getApplicationContext(), "" + index, Toast.LENGTH_LONG).show();
editor = prefs.edit();
int i = 1;
while (i < index) {
String s = "" + i;
String path = getPath(this, Uri.parse(prefs.getString(s, "string")));
final ImageView iv = new ImageView(this);
Bitmap b = null;
try {
b = getThumbnail(getContentResolver(), path);
} catch (Exception e) {
e.printStackTrace();
}
iv.setImageBitmap(b);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300, 300);
iv.setLayoutParams(layoutParams);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addImageBetweentext(iv.getDrawable());
}
});
grid.addView(iv);
i++;
}
keyboard.setOnClickListener(this);
camera.setOnClickListener(this);
take.setOnClickListener(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//camera
String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.DATA};
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null,
MediaStore.MediaColumns.DATE_ADDED + " DESC");
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(columnIndex);
cursor.close();
Uri uri = Uri.fromFile(new File(path));
int i = prefs.getInt("index", 1);
i++;
editor.putInt("index", i);
editor.putString("" + i, uri.toString());
editor.commit();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
this.sendBroadcast(mediaScanIntent);
Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
Bitmap b = null;
try {
b = getThumbnail(getContentResolver(), path);
} catch (Exception e) {
e.printStackTrace();
}
final ImageView iv = new ImageView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300, 300);
iv.setLayoutParams(layoutParams);
iv.setImageBitmap(b);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addImageBetweentext(iv.getDrawable());
}
});
grid.addView(iv);
}
if (requestCode == 2) {
//from gallery
Uri uri = data.getData();
int i = prefs.getInt("index", 1);
i++;
editor.putInt("index", i);
editor.putString("" + i, uri.toString());
editor.commit();
Toast.makeText(getApplicationContext(), prefs.getString("1", "string"), Toast.LENGTH_LONG).show();
final ImageView iv = new ImageView(this);
Bitmap b = null;
try {
b = getThumbnail(getContentResolver(), getPath(getApplicationContext(), uri));
} catch (Exception e) {
e.printStackTrace();
}
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(300, 300);
iv.setLayoutParams(layoutParams);
iv.setImageBitmap(b);
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addImageBetweentext(iv.getDrawable());
}
});
grid.addView(iv);
}
}
@Override
public void onClick(View v) {
View view = this.getCurrentFocus();
switch (v.getId()) {
case R.id.keyboard:
cameraLayout.setVisibility(View.GONE);
et.hasFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0);
}
break;
case R.id.camera:
cameraLayout.setVisibility(View.VISIBLE);
et.clearFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
break;
case R.id.take:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Insert a photo");
alert.setNegativeButton("Take from camera", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 1);
}
});
alert.setPositiveButton("Choose from gallery", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT, null);
gallery.setType("image/*");
gallery.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(gallery, "Select an image"), 2);
}
});
alert.show();
break;
}
}
public static Bitmap getThumbnail(ContentResolver cr, String path) throws Exception {
Cursor ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.MediaColumns._ID}, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
ca.close();
return null;
}
private void addImageBetweentext(Drawable drawable) {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
int selectionCursor = et.getSelectionStart();
et.getText().insert(selectionCursor, ".");
selectionCursor = et.getSelectionStart();
SpannableStringBuilder builder = new SpannableStringBuilder(et.getText());
builder.setSpan(new ImageSpan(drawable), selectionCursor - ".".length(), selectionCursor,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
et.setText(builder);
et.setSelection(selectionCursor);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
我需要用什么代码才能完成此操作?