继续上节,这次实现在记事本中添加照片功能。
首先,先给选项菜单的容器GridView添加点击事件监听器
bottomMenu = (GridView)findViewById(R.id.bottomMenu); //配置菜单 initBottomMenu(); //为菜单设置监听器 bottomMenu.setOnItemClickListener(new MenuClickEvent());
接着,在监听器里实现打开图库选择图片,并加图片返回,主要代码为:
//设置菜单项监听器 class MenuClickEvent implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent; //添加图片的主要代码 intent = new Intent(); //设定类型为image intent.setType("image/*"); //设置action intent.setAction(Intent.ACTION_GET_CONTENT); //选中相片后返回本Activity startActivityForResult(intent, 1); } }
最后, 因为用了startActivityForResult方法,所以需要实现onActivityResult方法,在该方法中将返回的照片添加在EditText中,在这里面也实现了对图片的等比例缩放,以至于不会充满整个屏幕。
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK){ //取得数据 Uri uri = data.getData(); ContentResolver cr = AddActivity.this.getContentResolver(); Bitmap bitmap = null; Bundle extras = null; //如果是选择照片 if(requestCode == 1){ try { //将对象存入Bitmap中 bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } int imgWidth = bitmap.getWidth(); int imgHeight = bitmap.getHeight(); double partion = imgWidth*1.0/imgHeight; double sqrtLength = Math.sqrt(partion*partion + 1); //新的缩略图大小 double newImgW = 480*(partion / sqrtLength); double newImgH = 480*(1 / sqrtLength); float scaleW = (float) (newImgW/imgWidth); float scaleH = (float) (newImgH/imgHeight); Matrix mx = new Matrix(); //对原图片进行缩放 mx.postScale(scaleW, scaleH); bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true); final ImageSpan imageSpan = new ImageSpan(this,bitmap); SpannableString spannableString = new SpannableString("test"); spannableString.setSpan(imageSpan, 0, spannableString.length(), SpannableString.SPAN_MARK_MARK); //光标移到下一行 et_Notes.append("\n"); Editable editable = et_Notes.getEditableText(); int selectionIndex = et_Notes.getSelectionStart(); spannableString.getSpans(0, spannableString.length(), ImageSpan.class); //将图片添加进EditText中 editable.insert(selectionIndex, spannableString); //添加图片后自动空出两行 et_Notes.append("\n\n"); } }
至此,在EditText中添加照片功能已实现。
下节,为记事本添加拍照功能。