通过GridView的点击事件弹出一个PopupWindows窗体,在通过窗体中的按钮来调用系统拍照功能,和从sd卡中查询图片。PopupWindows窗体布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/pop_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="@drawable/login_grey_btn"
android:gravity="center_horizontal"
android:orientation="vertical" >
<Button
android:id="@+id/btn_take_photo"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="拍照"
android:background="@drawable/btn_style_alert_dialog_button"
android:textStyle="bold"
/>
<Button
android:id="@+id/btn_pick_photo"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="5dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="从相册选择"
android:background="@drawable/btn_style_alert_dialog_button"
android:textStyle="bold"
/>
<Button
android:id="@+id/btn_cancel"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:layout_marginTop="15dip"
android:layout_marginBottom="15dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="取消"
android:background="@drawable/btn_style_alert_dialog_cancel"
android:textColor="#ffffff"
android:textStyle="bold"
/>
</LinearLayout>
</RelativeLayout>
PopupWindows类代码如下:
public class PopupWindows extends PopupWindow {
@SuppressWarnings("deprecation")
public PopupWindows(Context mContext, View parent) {
final View view = View.inflate(mContext, R.layout.photo_take, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
setWidth(LayoutParams.FILL_PARENT);
setHeight(LayoutParams.FILL_PARENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
Button camera = (Button) view.findViewById(R.id.btn_take_photo);
Button photo = (Button) view.findViewById(R.id.btn_pick_photo);
Button cancel = (Button) view.findViewById(R.id.btn_cancel);
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int height = view.findViewById(R.id.pop_layout)
.getTop();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_UP) {
if (y < height) {
dismiss();
}
}
return true;
}
});
camera.setOnClickListener(new OnClickListener() {//照相
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(sdcardTempFile));
startActivityForResult(intent, TAKE_PICTURE);
dismiss();
}
});
photo.setOnClickListener(new OnClickListener() {//相册
public void onClick(View v) {
// 激活系统图库,选择一张图片
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
startActivityForResult(intent, RESULT_LOAD_IMAGE);
dismiss();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
}
}
主活动布局为:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bg_blue"
android:orientation="vertical" >
<include layout="@layout/head" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/newspaper_rport_add_et_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dip"
android:layout_marginRight="16dip"
android:layout_marginTop="16dip"
android:layout_weight="3"
android:background="@drawable/current_text_bg"
android:hint="详细地址"
android:textColor="@color/color_gray_dark"
android:textSize="@dimen/tv_size_normal" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/newspaper_rport_add_et_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dip"
android:layout_marginRight="16dip"
android:layout_marginTop="16dip"
android:layout_weight="3"
android:background="@drawable/current_text_bg"
android:gravity="left|top"
android:hint="内容"
android:inputType="textMultiLine"
android:minLines="6"
android:scrollHorizontally="false"
android:textColor="@color/color_gray_dark"
android:textSize="@dimen/tv_size_normal" />
</LinearLayout>
<HorizontalScrollView
android:id="@+id/newsreport_selectimg_horizontalScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:scrollbars="@null" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<GridView
android:id="@+id/newspaper_reportScroll_gv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fastScrollEnabled="true"
android:focusable="true"
android:gravity="center"
android:horizontalSpacing="0dp"
android:numColumns="3"
android:scrollbars="none"
android:scrollingCache="false"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="1dp" >
</GridView>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
主活动NewspaperRportAddActivity类如下:
public class NewspaperRportAddActivity extends MyBaseActivity implements OnItemClickListener{
private static final int IMG_MAX = 3;
private static final int TAKE_PICTURE = 0;//拍照
private static final int RESULT_LOAD_IMAGE = 1;
private static final int CODE_CROP = 2;//裁剪
protected static final int NEWSPAPERRPORTADDSETDATA = 100;
private EditText naddress;
private EditText ncontent;
//上传图片
private GridView gridview;
private GridAdapter adapter;
private TextView pic;
private HorizontalScrollView selectimg_horizontalScrollView;
private List<Map<String, String>> mUrlList = new ArrayList<Map<String, String>>();
private List<String> drr = new ArrayList<String>();
private float dp;
private static List<Bitmap> bmp = new ArrayList<Bitmap>();
private int submitPositon = 0;
private File sdcardTempFile;
private Bitmap mbitMap;
private String naaddress = "";
private String naContent = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newspaper_report_add_activity);
//头像上传时使用到本地目录
File bDir = new File(AndroidUtils.getRootDirPath());
if(!bDir.exists())
bDir.mkdirs();
sdcardTempFile = new File(AndroidUtils.getRootDirPath() + "temp.jpg");
dp = getResources().getDimension(R.dimen.dp);
initWight();
initView();
}
/**
* initWight(这里用一句话描述这个方法的作用)
*/
private void initWight() {
selectimg_horizontalScrollView = (HorizontalScrollView) findViewById(R.id.newsreport_selectimg_horizontalScrollView);
gridview = (GridView) findViewById(R.id.newspaper_reportScroll_gv);
gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
gridviewInit();
}
public void gridviewInit() {
adapter = new GridAdapter(this);
adapter.setSelectedPosition(0);
int size = 0;
if (bmp.size() < 10) {
size = bmp.size() + 1;
} else {
size = bmp.size();
}
LayoutParams params = gridview.getLayoutParams();
final int width = size * (int) (dp * 9.4f);
params.width = width;
gridview.setLayoutParams(params);
//设置列的宽度
gridview.setColumnWidth((int) (dp * 9.4f));
//缩放模式
gridview.setStretchMode(GridView.NO_STRETCH);
//设置列数
gridview.setNumColumns(size);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(this);
selectimg_horizontalScrollView.getViewTreeObserver()
.addOnPreDrawListener(// 绘制完毕
new OnPreDrawListener() {
public boolean onPreDraw() {
selectimg_horizontalScrollView.scrollTo(width,
0);
selectimg_horizontalScrollView
.getViewTreeObserver()
.removeOnPreDrawListener(this);
return false;
}
});
}
private void initView() {
naddress = (EditText) findViewById(R.id.newspaper_rport_add_et_address);
ncontent = (EditText) findViewById(R.id.newspaper_rport_add_et_content);
}
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
if (position == bmp.size()) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (drr.size() >= IMG_MAX) {
Toast.makeText(getApplicationContext(),"最多只能上传" + IMG_MAX + "张图片", Toast.LENGTH_SHORT).show();
return;
}
new PopupWindows(NewspaperRportAddActivity.this, gridview);
} else {
Toast.makeText(getApplicationContext(), "sdcard已拔出,不能选择照片",
Toast.LENGTH_SHORT).show();
}
}
}
public class PopupWindows extends PopupWindow {
@SuppressWarnings("deprecation")
public PopupWindows(Context mContext, View parent) {
final View view = View.inflate(mContext, R.layout.photo_take, null);
view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins));
setWidth(LayoutParams.FILL_PARENT);
setHeight(LayoutParams.FILL_PARENT);
setBackgroundDrawable(new BitmapDrawable());
setFocusable(true);
setOutsideTouchable(true);
setContentView(view);
showAtLocation(parent, Gravity.BOTTOM, 0, 0);
update();
Button camera = (Button) view.findViewById(R.id.btn_take_photo);
Button photo = (Button) view.findViewById(R.id.btn_pick_photo);
Button cancel = (Button) view.findViewById(R.id.btn_cancel);
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
int height = view.findViewById(R.id.pop_layout)
.getTop();
int y = (int) event.getY();
if (event.getAction() == MotionEvent.ACTION_UP) {
if (y < height) {
dismiss();
}
}
return true;
}
});
camera.setOnClickListener(new OnClickListener() {//照相
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(sdcardTempFile));
startActivityForResult(intent, TAKE_PICTURE);
dismiss();
}
});
photo.setOnClickListener(new OnClickListener() {//相册
public void onClick(View v) {
// 激活系统图库,选择一张图片
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY
startActivityForResult(intent, RESULT_LOAD_IMAGE);
dismiss();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PICTURE://照相
if (resultCode != -1)
return;
try {
cropImage(Uri.fromFile(sdcardTempFile), 400, 300,CODE_CROP);//图片裁剪
} catch (Exception e) {
e.printStackTrace();
}
break;
case RESULT_LOAD_IMAGE://相册
if (data == null || resultCode != -1)
return;
try {
String myfilePath;
Uri selectedImageUri = data.getData();
if (selectedImageUri == null)
return;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cropImage(Uri.fromFile(new File(picturePath)), 400, 300,CODE_CROP);//图片裁剪
} catch (Exception e) {
e.printStackTrace();
Log.i("pmp","相册加载图片异常");
}
break;
case CODE_CROP://裁剪
setBitmapImage(data);
break;
}
}
private void setBitmapImage(Intent picdata) {
String myfilePath;
Bundle bundle = picdata.getExtras();
if (bundle != null)
{
Bitmap photo = bundle.getParcelable("data");
String filePath = saveBitmap2file(photo);
myfilePath = filePath;
drr.add(myfilePath);
bmp.add(Bimp.createFramedPhoto(480, 480, BitmapFactory.decodeFile(myfilePath),(int) (dp * 1.6f)));
gridviewInit();
}
}
private void cropImage(Uri uri, int outputX, int outputY,int requestId) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// crop为true是设置在开启的intent中设置显示的view可以剪裁
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 4);
intent.putExtra("aspectY", 3);
// outputX,outputY 是剪裁图片的宽高
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("return-data", true);
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, requestId);
}
// 使用系统当前日期加以调整作为照片的名称
private String getPhotoFileName() {
return AndroidUtils.getCurDate("'IMG'_yyyyMMdd_HHmmss") + ".jpg";
}
//图片格式转换
private String saveBitmap2file(Bitmap bmp) {
String filename = AndroidUtils.getRootDirPath() + getPhotoFileName();
CompressFormat format = CompressFormat.JPEG;
int quality = 100;
OutputStream stream = null;
try {
stream = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bmp.compress(format, quality, stream)) {
try { stream.close(); } catch (IOException e) { e.printStackTrace(); }
bmp.recycle();
return filename;
} else {
try { stream.close(); } catch (IOException e) { e.printStackTrace(); }
bmp.recycle();
return "";
}
}
public class GridAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int selectedPosition = -1;
private boolean shape;
public GridAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public boolean isShape() {
return shape;
}
public void setShape(boolean shape) {
this.shape = shape;
}
public class ViewHolder {
public ImageView image;
public Button bt;
}
public int getCount() {
if (bmp.size() < 10) {
return bmp.size() + 1;
} else {
return bmp.size();
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
public int getSelectedPosition() {
return selectedPosition;
}
/**
* ListView Item设置
*/
public View getView(int position, View convertView, ViewGroup parent) {
final int sign = position;
// 自定义视图
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
// 获取list_item布局文件的视图
convertView = inflater.inflate(R.layout.item_published_grida,
null);
// 获取控件对象
holder.image = (ImageView) convertView
.findViewById(R.id.item_grida_image);
holder.bt = (Button) convertView
.findViewById(R.id.item_grida_bt);
// 设置控件集到convertView
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == bmp.size()) {
holder.image.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.icon_addpic_unfocused));
holder.bt.setVisibility(View.GONE);
if (position == 9) {
holder.image.setVisibility(View.GONE);
}
} else {
holder.image.setImageBitmap(bmp.get(position));
holder.bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
bmp.get(sign).recycle();
bmp.remove(sign);
drr.remove(sign);
gridviewInit();
}
});
}
return convertView;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i("pmp","清理图片缓存");
sdcardTempFile.delete();
// 清理图片缓存
for (int i = 0; i < bmp.size(); i++) {
bmp.get(i).recycle();
Log.i("pmp","drr.get(i)" + drr.get(i));
File file = new File(drr.get(i));
if(file.delete()){
Log.i("pmp","清理图片缓存成功");
}
}
bmp.clear();
drr.clear();
}
}
这样就可以再GridView中显示自己手机相册中和自己拍的图片了。