点击头像事件:
case R.id.myself_edit_rl_img:
//点击头像
if (popupwindow != null&&popupwindow.isShowing()) {
popupwindow.dismiss();
return;
} else {
//检查写入权限
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//拥有读写文件权限
Log.i(TAG,"拥有读写文件权限");
initmPopupWindowView();
}else{
Log.i(TAG,"没有读写权限");
//没有读写权限
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)){
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
140);
}else{
showPermissionDialog();
}
}
}
break;
弹出来选择拍照还是在相册中选择:
public void initmPopupWindowView() {
// 利用layoutInflater获得View
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// // 获取自定义布局文件pop.xml的视图
View view = inflater.inflate(R.layout.popview, null);
// 创建PopupWindow实例,200,150分别是宽度和高度
// popupwindow = new PopupWindow(customView, 200, 250);
// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
popupwindow = new PopupWindow(view,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT);
// 设置动画效果 [R.style.AnimationFade 是自己事先定义好的]
// 设置popWindow弹出窗体可点击,这句话必须添加,并且是true
popupwindow.setFocusable(true);
// 实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(0xb0000000);
popupwindow.setBackgroundDrawable(dw);
popupwindow.setOutsideTouchable(true);// 触摸popupwindow外部,popupwindow消失
backgroundAlpha(0.5f);//0.0-1.0
// 设置popWindow的显示和消失动画
popupwindow.setAnimationStyle(R.style.AnimationFade);
// 在底部显示
popupwindow.showAtLocation(activity.findViewById(R.id.activity_myself__edit),
Gravity.BOTTOM, 0, 0);
popupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
//popupwindow消失的时候恢复成原来的透明度
backgroundAlpha(1f);
}
});
// 这里检验popWindow里的button是否可以点击
Button first = (Button) view.findViewById(R.id.first);
first.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"第一个按钮被点击了");
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// your code using Camera API here - is between 1-20
ForToast.showToast("请开启照相机权限后重试",activity);
Log.i(TAG,"our code using Camera API here - is between 1-20");
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// your code using Camera2 API here - is api 21 or higher
Log.i(TAG,"your code using Camera2 API here - is api 21 or higher");
String CAMERA_PERMISSION=Manifest.permission.CAMERA;
if(ContextCompat.checkSelfPermission(activity,CAMERA_PERMISSION)==PackageManager.PERMISSION_GRANTED){
//授予权限了
choseHeadImageFromCameraCapture();
}else{
if(ActivityCompat.shouldShowRequestPermissionRationale(activity,CAMERA_PERMISSION)){
//还没有完全禁止
ActivityCompat.requestPermissions(activity,new String[]{CAMERA_PERMISSION},110);
}else{
//完全禁止了
showPermissionDialog();
}
}
}
}catch (Exception e){
Log.i(TAG,"错误了"+e.toString());
}
//点击空白区域
if(popupwindow!=null){
popupwindow.dismiss();
}
}
});
Button second = (Button) view.findViewById(R.id.second);
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"第2个按钮被点击了");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// your code using Camera API here - is between 1-20
ForToast.showToast("请开启照相机权限后重试",activity);
Log.i(TAG,"our code using Camera API here - is between 1-20");
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// your code using Camera2 API here - is api 21 or higher
Log.i(TAG,"your code using Camera2 API here - is api 21 or higher");
String CAMERA_PERMISSION=Manifest.permission.CAMERA;
if(ContextCompat.checkSelfPermission(activity,CAMERA_PERMISSION)==PackageManager.PERMISSION_GRANTED){
//授予权限了
choseHeadImageFromGallery();
}else{
if(ActivityCompat.shouldShowRequestPermissionRationale(activity,CAMERA_PERMISSION)){
//还没有完全禁止
ActivityCompat.requestPermissions(activity,new String[]{CAMERA_PERMISSION},120);
}else{
//完全禁止了
showPermissionDialog();
}
}
}
if(popupwindow!=null){
popupwindow.dismiss();
}
}
});
Button third = (Button) view.findViewById(R.id.third);
third.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG,"第3个按钮被点击了");
if(popupwindow!=null){
popupwindow.dismiss();
}
return;
}
});
}
弹出popwindow对应xml: popview.xml:
响应权限请求事件的返回:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 110:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
choseHeadImageFromCameraCapture();
//点击空白区域
if(popupwindow!=null){
popupwindow.dismiss();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission
showPermissionDialog();
}
break;
case 120:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
choseHeadImageFromGallery();
//点击空白区域
if(popupwindow!=null){
popupwindow.dismiss();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission
showPermissionDialog();
}
break;
case 140:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
initmPopupWindowView();;
//点击空白区域
if(popupwindow!=null){
popupwindow.dismiss();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission
showPermissionDialog();
}
break;
// other 'case' lines to check for other
// permissions this app might request
}
}
完全禁止时弹出提示框
private static final String PACKAGE_URL_SCHEME = "package:";
private void showPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("帮助");
builder.setMessage(MyApplication.Permisssion);
// 拒绝, 退出应用
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
// setResult(PERMISSIONS_DENIED);
}
});
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
startActivity(intent);
}
});
builder.setCancelable(false);
builder.show();
}
相机操作:
/**
* 设置添加屏幕的背景透明度
* @param bgAlpha
*/
/**
* 设置添加屏幕的背景透明度
* @param bgAlpha
*/
public void backgroundAlpha(float bgAlpha)
{
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0
getWindow().setAttributes(lp);
}
// 从本地相册选取图片作为头像
private void choseHeadImageFromGallery() {
Intent intentFromGallery = new Intent();
// 设置文件类型
intentFromGallery.setType("image/*");
intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
}
// 启动手机相机拍摄照片作为头像
private void choseHeadImageFromCameraCapture() {
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可用,存储照片文件
if (hasSdcard()) {
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
.fromFile(new File(myApplication.IMAGE_FILE_NAME_HEAD)));
}
startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
// 用户没有进行有效的设置操作,返回
if (resultCode == RESULT_CANCELED) {
return;
}
switch (requestCode) {
case CODE_GALLERY_REQUEST:
//选择相册返回值
cropRawPhoto(intent.getData());
break;
case CODE_CAMERA_REQUEST:
if (hasSdcard()) {
File tempFile = new File(myApplication.IMAGE_FILE_NAME_HEAD);
if(!tempFile.exists())
//创建文件
try {
tempFile.createNewFile();
} catch (IOException e) {
Log.i(TAG,e.toString());
Toast.makeText(getApplication(), "图片保存失败!", Toast.LENGTH_LONG)
.show();
}
cropRawPhoto(Uri.fromFile(tempFile));
} else {
Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)
.show();
}
break;
case CODE_RESULT_REQUEST:
if (intent != null) {
//将Uri图片转换为Bitmap
try {
Bitmap bitmap2 = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
setImageToHeadView(bitmap2);
} catch (FileNotFoundException e) {
Toast.makeText(getApplication(), "图片剪切失败!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, intent);
}
/**
* 裁剪原始的图片
*/
public void cropRawPhoto(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX , aspectY :宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
/*// outputX , outputY : 裁剪图片宽高
intent.putExtra("outputX", output_X);
intent.putExtra("outputY", output_Y);
intent.putExtra("return-data", true);*/
/**
* 此方法返回的图片只能是小图片(sumsang测试为高宽160px的图片)
* 故将图片保存在Uri中,调用时将Uri转换为Bitmap,此方法还可解决miui系统不能return data的问题
*/
//intent.putExtra("return-data", true);
//uritempFile为Uri类变量,实例化uritempFile
uritempFile = Uri.parse("file://" + "/" + MyApplication.IMAGE_FILE_NAME_HEAD);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, CODE_RESULT_REQUEST);
}
/**
* 提取保存裁剪之后的图片数据,并设置头像部分的View
*/
private void setImageToHeadView(Bitmap bitmap1) {
Log.i(TAG,"从本地相册选取图片作为头像3");
if (bitmap1 != null) {
p= ForBitmap.getPhotoFileName(bitmap1);
myself_edit__iv_img.setImageBitmap(bitmap1);
cd = ForDialog.show(activity, "正在上传头像...");
uploadImg();
}
}
/**
* 检查设备是否存在SDCard的工具方法
*/
public static boolean hasSdcard() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
// 有存储的SDCard
return true;
} else {
return false;
}
}
其中:
public static String Permisssion="当前应用缺少必要权限。请点击\"设置\"-打开所需权限。";
效果图展示: