我在这里有一个Android ListView,名为" mConversationView"在这段代码中:
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.phoji.common.logger.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Calendar;
public class BluetoothChatFragment extends Fragment {
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_ENABLE_BT = 3;
private static final String TAG = "BluetoothChatFragment";
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private ListView mConversationView;
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
FragmentActivity activity = BluetoothChatFragment.this.getActivity();
switch (msg.what) {
case BluetoothChatFragment.REQUEST_CONNECT_DEVICE_SECURE /*1*/:
switch (msg.arg1) {
case 0 /*0*/:
case BluetoothChatFragment.REQUEST_CONNECT_DEVICE_SECURE /*1*/:
BluetoothChatFragment.this.setStatus((int) R.string.title_not_connected);
return;
case BluetoothChatFragment.REQUEST_CONNECT_DEVICE_INSECURE /*2*/:
BluetoothChatFragment.this.setStatus((int) R.string.title_connecting);
return;
case BluetoothChatFragment.REQUEST_ENABLE_BT /*3*/:
BluetoothChatFragment bluetoothChatFragment = BluetoothChatFragment.this;
BluetoothChatFragment bluetoothChatFragment2 = BluetoothChatFragment.this;
Object[] objArr = new Object[BluetoothChatFragment.REQUEST_CONNECT_DEVICE_SECURE];
objArr[0] = BluetoothChatFragment.this.mConnectedDeviceName;
bluetoothChatFragment.setStatus(bluetoothChatFragment2.getString(R.string.title_connected_to, objArr));
BluetoothChatFragment.this.mConversationArrayAdapter.clear();
return;
default:
return;
}
case BluetoothChatFragment.REQUEST_CONNECT_DEVICE_INSECURE /*2*/:
BluetoothChatFragment.this.mConversationArrayAdapter.add(BluetoothChatFragment.this.mConnectedDeviceName + ": " + new String((byte[]) msg.obj, 0, msg.arg1));
return;
case BluetoothChatFragment.REQUEST_ENABLE_BT /*3*/:
BluetoothChatFragment.this.mConversationArrayAdapter.add("Me: " + new String((byte[]) msg.obj));
return;
case Log.INFO /*4*/:
BluetoothChatFragment.this.mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (activity != null) {
Toast.makeText(activity, "Connected to " + BluetoothChatFragment.this.mConnectedDeviceName, Toast.LENGTH_LONG).show();
return;
}
return;
case Log.WARN /*5*/:
if (activity != null) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST), Toast.LENGTH_LONG).show();
return;
}
return;
default:
return;
}
}
};
private EditText mOutEditText;
private StringBuffer mOutStringBuffer;
private Button mSendButton;
private LinearLayout inputInterface;
Button keyboard, camera, take;
LinearLayout cameraLayout;
GridLayout grid;
SharedPreferences prefs;
SharedPreferences.Editor editor;
static int index;
private OnEditorActionListener mWriteListener = new OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
if (actionId == 0 && event.getAction() == BluetoothChatFragment.REQUEST_CONNECT_DEVICE_SECURE) {
BluetoothChatFragment.this.sendMessage(view.getText().toString());
}
return true;
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (this.mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
@Override
public void onStart() {
super.onStart();
if (!this.mBluetoothAdapter.isEnabled()) {
startActivityForResult(new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE"), REQUEST_ENABLE_BT);
} else if (this.mChatService == null) {
setupChat();
}
}
public void onDestroy() {
super.onDestroy();
if (this.mChatService != null) {
this.mChatService.stop();
}
}
public void onResume() {
super.onResume();
if (this.mChatService != null && this.mChatService.getState() == 0) {
this.mChatService.start();
}
}
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
this.mConversationView = (ListView) view.findViewById(R.id.in);
this.mOutEditText = (EditText) view.findViewById(R.id.edit_text_out);
this.mSendButton = (Button) view.findViewById(R.id.button_send);
inputInterface = (LinearLayout) view.findViewById(R.id.inputInterface);
keyboard = (Button) view.findViewById(R.id.keyboard);
camera = (Button) view.findViewById(R.id.camera);
take = (Button) view.findViewById(R.id.take);
cameraLayout = (LinearLayout) view.findViewById(R.id.cameraLayout);
cameraLayout.setVisibility(View.GONE);
grid = (GridLayout) view.findViewById(R.id.grid);
}
private void setupChat() {
Log.d(TAG, "setupChat()");
this.mConversationArrayAdapter = new ArrayAdapter(getActivity(), R.layout.message);
this.mConversationView.setAdapter(this.mConversationArrayAdapter);
this.mOutEditText.setOnEditorActionListener(this.mWriteListener);
inputInterface.setVisibility(View.GONE);
prefs = getActivity().getSharedPreferences("stuff", Context.MODE_PRIVATE);
index = prefs.getInt("index", 1);
editor = prefs.edit();
int i = 2;
while (i <= index) {
String s = "" + i;
String path = getPath(getActivity(), Uri.parse(prefs.getString(s, "string")));
final ImageView iv = new ImageView(getContext());
Bitmap b = null;
try {
b = getResizedBitmap(100,100,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(new View.OnClickListener() {
@Override
public void onClick(View view) {
cameraLayout.setVisibility(View.GONE);
mOutEditText.hasFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mOutEditText, 0);
}
}
});
camera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
cameraLayout.setVisibility(View.VISIBLE);
mOutEditText.clearFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
take.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder dalert = new AlertDialog.Builder(getActivity());
dalert.setTitle("Insert a photo");
dalert.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, 10);
}
});
dalert.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.putExtra("return-data", true);
gallery.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(gallery, "Select an image"), 20);
}
});
dalert.show();
/*
Dialog dialog = new Dialog(getContext());
dialog.setTitle("Insert a photo");
Button n = new Button(getContext());
n.setText("Take from camera");
n.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 10);
}
});
Button p = new Button(getContext());
p.setText("Choose from gallery");
p.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent gallery = new Intent(Intent.ACTION_GET_CONTENT, null);
gallery.setType("image*//*");
gallery.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(gallery, "Select an image"), 20);
}
});
dialog.show();*/
}
});
this.mOutEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
inputInterface.setVisibility(View.VISIBLE);
} else {
inputInterface.setVisibility(View.GONE);
}
}
});
this.mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View view = BluetoothChatFragment.this.getView();
if (view != null) {
BluetoothChatFragment.this.sendMessage(((TextView) view.findViewById(R.id.edit_text_out)).getText().toString());
}
}
});
this.mChatService = new BluetoothChatService(getActivity(), this.mHandler);
this.mOutStringBuffer = new StringBuffer(BuildConfig.VERSION_NAME);
}
public Bitmap getResizedBitmap(int targetW, int targetH, String imagePath) {
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
//inJustDecodeBounds = true <-- will not load the bitmap into memory
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
return(bitmap);
}
private void ensureDiscoverable() {
if (this.mBluetoothAdapter.getScanMode() != 23) {
Intent discoverableIntent = new Intent("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE");
discoverableIntent.putExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300);
startActivity(discoverableIntent);
}
}
private void sendMessage(String message) {
if (this.mChatService.getState() != REQUEST_ENABLE_BT) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_LONG).show();
} else if (message.length() > 0) {
this.mChatService.write(message.getBytes());
this.mOutStringBuffer.setLength(0);
this.mOutEditText.setText(this.mOutStringBuffer);
}
}
private void setStatus(int resId) {
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity != null) {
android.support.v7.app.ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(resId);
}
}
}
private void setStatus(CharSequence subTitle) {
AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity != null) {
android.support.v7.app.ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(subTitle);
}
}
}
private String savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
long seconds = System.currentTimeMillis();
extStorageDirectory+="/Pictures";
String imgName="IMG_"+seconds+".png";
extStorageDirectory+="/"+imgName;
if(!new File(extStorageDirectory).exists())
new File(extStorageDirectory).mkdir();
File file = new File(extStorageDirectory);
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory);
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
insertImageIntoGallery(getActivity().getContentResolver(),imgName,extStorageDirectory,"");
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getActivity().getApplicationContext().sendBroadcast(mediaScanIntent);
} catch (Exception e) {
e.printStackTrace();
return null;
}
Log.e("Test",extStorageDirectory);
Log.e("Test",extStorageDirectory);
return extStorageDirectory;
}
public void insertImageIntoGallery(ContentResolver cr,String path, String title, String description) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, title);
values.put(MediaStore.Images.Media.DISPLAY_NAME, title);
values.put(MediaStore.Images.Media.DESCRIPTION, description);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA,path);
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == 10) {
//camera
Bitmap photo = (Bitmap) data.getExtras().get("data");
String path = savebitmap(photo);
Uri uri = Uri.fromFile(new File(path));
int i = prefs.getInt("index", 1);
i++;
editor.putInt("index", i);
editor.putString("" + i, path);
editor.commit();
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(uri);
this.getActivity().sendBroadcast(mediaScanIntent);
Bitmap b = null;
try {
b = BitmapFactory.decodeFile(path);
} catch (Exception e) {
e.printStackTrace();
}
final ImageView iv = new ImageView(getContext());
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 == 20) {
//from gallery
Uri uri = data.getData();
int i = prefs.getInt("index", 1);
i++;
editor.putInt("index", i);
editor.putString("" + i, uri.toString());
editor.commit();
final ImageView iv = new ImageView(getContext());
Bitmap b = null;
try {
b = getThumbnail(getActivity().getContentResolver(), getPath(getContext(), 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);
}
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE /*1*/:
if (resultCode == -1) {
connectDevice(data, true);
return;
}
return;
case REQUEST_CONNECT_DEVICE_INSECURE /*2*/:
if (resultCode == -1) {
connectDevice(data, false);
return;
}
return;
case REQUEST_ENABLE_BT /*3*/:
if (resultCode == -1) {
setupChat();
return;
}
Log.d(TAG, "BT not enabled");
Toast.makeText(getActivity(), R.string.bt_not_enabled_leaving, Toast.LENGTH_LONG).show();
getActivity().finish();
return;
default:
return;
}
}
private void connectDevice(Intent data, boolean secure) {
this.mChatService.connect(this.mBluetoothAdapter.getRemoteDevice(data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS)), secure);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan /*2131361822*/:
startActivityForResult(new Intent(getActivity(), DeviceListActivity.class), REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.insecure_connect_scan /*2131361823*/:
startActivityForResult(new Intent(getActivity(), DeviceListActivity.class), REQUEST_CONNECT_DEVICE_INSECURE);
return true;
case R.id.discoverable /*2131361824*/:
ensureDiscoverable();
return true;
default:
return false;
}
}
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 = mOutEditText.getSelectionStart();
//et.setText(et.getText().toString()+" ");
mOutEditText.getText().insert(selectionCursor, " ");
selectionCursor = mOutEditText.getSelectionStart();
SpannableStringBuilder builder = new SpannableStringBuilder(mOutEditText.getText());
builder.setSpan(new ImageSpan(drawable), selectionCursor-1 , selectionCursor,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mOutEditText.setText(builder);
mOutEditText.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());
}
}
如何使用支持图像的TextView替换它或使此ListView支持EditText mOutEditText输入的图像?
答案 0 :(得分:0)
好的!为此,您需要使用API 1中的SpannableStringBuilder,如下所示:
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("My string. I ")
.append(" ", new ImageSpan(getActivity(), R.drawable.ic_action_heart), 0)
.append(" Cree by Dexode");
textView.setText(builder);