美文网首页安卓开发技术汇
Android弹窗之PopupWindow-更换头像

Android弹窗之PopupWindow-更换头像

作者: 不朽大叔丶 | 来源:发表于2019-07-21 18:51 被阅读0次

还是先上图


PopupWindow.jpg

1.新建一个类PhotoPopupWindow

/**
 * Created by Administrator on 2019/7/16 0016.
 */

public class PhotoPopupWindow extends PopupWindow {

    private View mView; // PopupWindow 菜单布局
    private Context mContext; // 上下文参数
    private View.OnClickListener mSelectListener; // 相册选取的点击监听器
    private View.OnClickListener mCaptureListener; // 拍照的点击监听器

    public PhotoPopupWindow(Activity context, View.OnClickListener selectListener, View.OnClickListener captureListener) {
        super(context);
        this.mContext = context;
        this.mSelectListener = selectListener;
        this.mCaptureListener = captureListener;
        init();
    }

    /**
     * 设置布局以及点击事件
     */
    private void init() {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view= inflater.inflate(R.layout.popu_layout, null);
        Button btn_camera = (Button) mView.findViewById(R.id.btn_camera);
        Button btn_select = (Button) mView.findViewById(R.id.btn_select);
        Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
        btn_select.setOnClickListener(mSelectListener);
        btn_camera.setOnClickListener(mCaptureListener);
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        // 导入布局
        this.setContentView(mView);
        // 设置动画效果
        this.setAnimationStyle(R.style.popwindow_anim_style);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置可触
        this.setFocusable(true);
        ColorDrawable drawable = new ColorDrawable(0x0000000);
        this.setBackgroundDrawable(drawable );
        // 单击弹出窗以外关闭窗口
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height = mView.findViewById(R.id.ll_pop).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }
}

2.popu_layout.xml 布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#66000000">

    <LinearLayout
        android:id="@+id/ll_pop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dp_15"
        android:layout_marginRight="@dimen/dp_15"
        android:orientation="vertical"
        android:layout_alignParentBottom="true">
        <Button
            android:id="@+id/icon_btn_camera"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/white_btn_top"
            android:textColor="@color/colorMainGreen"
            android:text="拍照"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="@dimen/dp_1"
            android:background="#eee"/>
        <Button
            android:id="@+id/icon_btn_select"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/white_btn_bottom"
            android:textColor="@color/colorMainGreen"
            android:text="相册选择"/>
        <Button
            android:id="@+id/icon_btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:layout_marginBottom="@dimen/dp_15"
            android:background="@drawable/white_btn"
            android:textColor="@color/colorMainGreen"
            android:text="取消"/>
    </LinearLayout>

</RelativeLayout>

white_btn_top.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white" />
    <corners android:topLeftRadius="@dimen/dp_10"
        android:topRightRadius="@dimen/dp_10"
        android:bottomRightRadius="0dp"
        android:bottomLeftRadius="0dp"/>
    <stroke android:width="0dp" android:color="@android:color/white" />
</shape>

white_btn_bottom.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white" />
    <corners android:topLeftRadius="0dp"
        android:topRightRadius="0dp"
        android:bottomRightRadius="@dimen/dp_10"
        android:bottomLeftRadius="@dimen/dp_10"/>
    <stroke android:width="0dp" android:color="@android:color/white" />
</shape>

white_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners android:radius="@dimen/dp_10"/>
    <stroke android:width="0dp" android:color="@android:color/white" />
</shape>

显示及关闭动画
1.在style中添加:

<style name="popwindow_anim_style">
        <item name="android:windowEnterAnimation">@anim/popup_show</item>
        <item name="android:windowExitAnimation">@anim/popup_gone</item>
    </style>

2.在res下新建anim文件夹
2.1 新建popup_show.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>
  2.2  新建popup_gone.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha
        android:duration="200"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>

OK, 完成!
在页面中引用:

PhotoPopupWindow mPhotoPopupWindow = new PhotoPopupWindow(调用页面.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 进入相册选择
                        System.out.println("进入相册选择");
                        // 文件权限申请
                        if (ContextCompat.checkSelfPermission(UserInfoActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            // 权限还没有授予,进行申请
                            ActivityCompat.requestPermissions(UserInfoActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200); // 申请的 requestCode 为 200
                        } else {
                            // 如果权限已经申请过,直接进行图片选择
                            mPhotoPopupWindow.dismiss();
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            // 判断系统中是否有处理该 Intent 的 Activity
                            if (intent.resolveActivity(getPackageManager()) != null) {
                                startActivityForResult(intent, REQUEST_IMAGE_GET);
                            } else {
                                Toast.makeText(UserInfoActivity.this, "未找到图片查看器", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 拍照
                        System.out.println("拍照");
                        // 拍照及文件权限申请
                        if (ContextCompat.checkSelfPermission(调用页面.this,
                                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                                || ContextCompat.checkSelfPermission(调用页面.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            // 权限还没有授予,进行申请
                            ActivityCompat.requestPermissions(调用页面.this,
                                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300); // 申请的 requestCode 为 300
                        } else {
                            // 权限已经申请,直接拍照
                            mPhotoPopupWindow.dismiss();
                            CameraUtil.openCamera(调用页面.this);
                        }
                    }
                });
                View rootView = LayoutInflater.from(调用页面.this).inflate(调用页面的布局, null);
                mPhotoPopupWindow.showAtLocation(rootView,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

以上就是关于PopupWindow的所有。

下面附上一个调用系统相机的工具类,亲测可用,妈妈再也不用担心我的fileprovider了!!

public class CameraUtil {
    public static File tempFile;
    public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    public static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 2;// 拍摄视频
    private static final String IMAGE_FILE_NAME = "icon.jpg";
    /**
     * 打开相机拍照
     *
     * @param activity
     */
    public static void openCamera(Activity activity) {
        //获取系统版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用,可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    filename + ".jpg");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                Uri uri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
        }
        // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CAREMA
        activity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }


    /**
     * 打开相机录像
     */
    public static void startToVideo(Activity activity) {
        //獲取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        Uri fileUri = null;
        File file = null;
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        try {
            file = createMediaFile();
            if (file.exists()) {
                fileUri = Uri.fromFile(file); // create a file to save the video
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (currentapiVersion < 24) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
        } else {
            //兼容android7.0
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            Uri uri = activity.getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // start the Video Capture Intent
        activity.startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
    }

    /*
   * 判断sdcard是否被挂载
   */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 创建保存录制得到的视频文件
     *
     * @return
     * @throws IOException
     */
    public static File createMediaFile() throws IOException {
        if (hasSdcard()) {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_MOVIES), "CameraVideos");
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "VID_" + timeStamp;
            String suffix = ".mp4";
            File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
            return mediaFile;
        }
        return null;
    }
}

权限处理回调

/**
     * 处理权限回调结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 200:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPhotoPopupWindow.dismiss();
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    // 判断系统中是否有处理该 Intent 的 Activity
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivityForResult(intent, REQUEST_IMAGE_GET);
                    } else {
                        MyToast.getToast(getApplicationContext(), "未找到图片查看器!");
                    }
                } else {
                    mPhotoPopupWindow.dismiss();
                    MyToast.getToast(getApplicationContext(), "权限被拒绝无法使用该功能!");
                }
                break;
            case 300:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPhotoPopupWindow.dismiss();
                    CameraUtil.openCamera(UserInfoActivity.this);
                } else {
                    mPhotoPopupWindow.dismiss();
                    MyToast.getToast(getApplicationContext(), "权限被拒绝无法使用该功能!");
                }
                break;
        }
    }

相机 相册回调处理

    private static final int REQUEST_IMAGE_GET = 0;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 回调成功
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 相册选取
                case REQUEST_IMAGE_GET:
                    try {
                        Uri uri = data.getData();
                        userInfoRiv.setImageURI(uri);
                        //根据uri获取bitmap

                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                    break;

                // 拍照
                case REQUEST_IMAGE_CAPTURE:
                    System.out.println("拍照返回成功");
                    Uri uri = Uri.fromFile(CameraUtil.tempFile);
                    userInfoRiv.setImageURI(uri);
                    break;
            }
        }
    }

里面用到的自定义MyToast类,有兴趣的可以了解下!

相关文章

  • Android弹窗之PopupWindow-更换头像

    还是先上图 1.新建一个类PhotoPopupWindow 2.popu_layout.xml 布局文件 whit...

  • Android相机适配代码封装

    在Android项目中,少不了需要更换头像这样一个小需求。然而一个看似简单的更换头像操作,对于Android开发者...

  • Android Picasso不缓存图片

    Android Picasso不缓存图片 问题描述:大多APP都有更换个人头像的功能,楼主在开发中遇到了当更换头像...

  • 实现一个Android中更换头像功能

    实现一个Android中更换头像功能 本文原创,转载请经过本人准许 写在前面: 更换头像这个功能在用户界面几乎是1...

  • 点击其他区域,关闭该弹窗

    工作时遇到一个问题。点击头像显示头像弹窗,点击其他区域,就关闭该弹窗。由于头像弹窗是一个单独的组件,怎么监听头像弹...

  • Glide如何加载同一URL下的最新图片

    简述 基于项目需求,用户更换新头像后,iOS、Android、web 端三端需要能更新到最新的头像。由于各种原因,...

  • Android更换头像 适配7.0

    更换头像是个对一群人毫无存在感的功能,但是对另外一群人炒鸡常用的功能。 6.0相机需要申请动态权限,7.0认为直接...

  • vue 更换头像2

    上一篇说到了项目中需要的更换头像功能,但是在做这个功能的时候也有遇到一些小问题比如说在更换头像后,显示的头像还是之...

  • 产品喵的日常(4)

    对研发的需求Y&N NO:有头像的地方点头像都应该可以更换头像 YES:顶部导航头像点击可更换头像,e-HR中基本...

  • 更换头像

    微信头像各种各样,一般由个人的喜好,心情、性格决定。决定选择什么样的物件呢?有的人是随意选的,不过有的人是...

网友评论

    本文标题:Android弹窗之PopupWindow-更换头像

    本文链接:https://www.haomeiwen.com/subject/hssvlctx.html