Android彈窗之PopupWindow-更換頭像

還是先上圖


PopupWindow.jpg

1.新建一個(gè)類PhotoPopupWindow

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

public class PhotoPopupWindow extends PopupWindow {

    private View mView; // PopupWindow 菜單布局
    private Context mContext; // 上下文參數(shù)
    private View.OnClickListener mSelectListener; // 相冊(cè)選取的點(diǎn)擊監(jiān)聽器
    private View.OnClickListener mCaptureListener; // 拍照的點(diǎn)擊監(jiān)聽器

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

    /**
     * 設(shè)置布局以及點(diǎn)擊事件
     */
    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();
            }
        });

        // 導(dǎo)入布局
        this.setContentView(mView);
        // 設(shè)置動(dòng)畫效果
        this.setAnimationStyle(R.style.popwindow_anim_style);
        this.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        // 設(shè)置可觸
        this.setFocusable(true);
        ColorDrawable drawable = new ColorDrawable(0x0000000);
        this.setBackgroundDrawable(drawable );
        // 單擊彈出窗以外關(guān)閉窗口
        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="相冊(cè)選擇"/>
        <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>

顯示及關(guān)閉動(dòng)畫
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(調(diào)用頁面.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 進(jìn)入相冊(cè)選擇
                        System.out.println("進(jìn)入相冊(cè)選擇");
                        // 文件權(quán)限申請(qǐng)
                        if (ContextCompat.checkSelfPermission(UserInfoActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            // 權(quán)限還沒有授予芝发,進(jìn)行申請(qǐng)
                            ActivityCompat.requestPermissions(UserInfoActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200); // 申請(qǐng)的 requestCode 為 200
                        } else {
                            // 如果權(quán)限已經(jīng)申請(qǐng)過,直接進(jìn)行圖片選擇
                            mPhotoPopupWindow.dismiss();
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            // 判斷系統(tǒng)中是否有處理該 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("拍照");
                        // 拍照及文件權(quán)限申請(qǐng)
                        if (ContextCompat.checkSelfPermission(調(diào)用頁面.this,
                                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                                || ContextCompat.checkSelfPermission(調(diào)用頁面.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            // 權(quán)限還沒有授予苛谷,進(jìn)行申請(qǐng)
                            ActivityCompat.requestPermissions(調(diào)用頁面.this,
                                    new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 300); // 申請(qǐng)的 requestCode 為 300
                        } else {
                            // 權(quán)限已經(jīng)申請(qǐng)辅鲸,直接拍照
                            mPhotoPopupWindow.dismiss();
                            CameraUtil.openCamera(調(diào)用頁面.this);
                        }
                    }
                });
                View rootView = LayoutInflater.from(調(diào)用頁面.this).inflate(調(diào)用頁面的布局, null);
                mPhotoPopupWindow.showAtLocation(rootView,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

以上就是關(guān)于PopupWindow的所有。

下面附上一個(gè)調(diào)用系統(tǒng)相機(jī)的工具類腹殿,親測(cè)可用独悴,媽媽再也不用擔(dān)心我的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";
    /**
     * 打開相機(jī)拍照
     *
     * @param activity
     */
    public static void openCamera(Activity activity) {
        //獲取系統(tǒng)版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相機(jī)
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判斷存儲(chǔ)卡是否可以用刻炒,可用進(jìn)行存儲(chǔ)
        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) {
                // 從文件中創(chuàng)建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);
            }
        }
        // 開啟一個(gè)帶有返回值的Activity,請(qǐng)求碼為PHOTO_REQUEST_CAREMA
        activity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }


    /**
     * 打開相機(jī)錄像
     */
    public static void startToVideo(Activity activity) {
        //獲取系統(tǒng)版本
        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);
    }

    /**
     * 創(chuàng)建保存錄制得到的視頻文件
     *
     * @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;
    }
}

權(quán)限處理回調(diào)

/**
     * 處理權(quán)限回調(diào)結(jié)果
     */
    @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/*");
                    // 判斷系統(tǒng)中是否有處理該 Intent 的 Activity
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        startActivityForResult(intent, REQUEST_IMAGE_GET);
                    } else {
                        MyToast.getToast(getApplicationContext(), "未找到圖片查看器自沧!");
                    }
                } else {
                    mPhotoPopupWindow.dismiss();
                    MyToast.getToast(getApplicationContext(), "權(quán)限被拒絕無法使用該功能坟奥!");
                }
                break;
            case 300:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mPhotoPopupWindow.dismiss();
                    CameraUtil.openCamera(UserInfoActivity.this);
                } else {
                    mPhotoPopupWindow.dismiss();
                    MyToast.getToast(getApplicationContext(), "權(quán)限被拒絕無法使用該功能!");
                }
                break;
        }
    }

相機(jī) 相冊(cè)回調(diào)處理

    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) {
        // 回調(diào)成功
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 相冊(cè)選取
                case REQUEST_IMAGE_GET:
                    try {
                        Uri uri = data.getData();
                        userInfoRiv.setImageURI(uri);
                        //根據(jù)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類,有興趣的可以了解下爱谁!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末晒喷,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子访敌,更是在濱河造成了極大的恐慌凉敲,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件寺旺,死亡現(xiàn)場離奇詭異荡陷,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)迅涮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來徽龟,“玉大人叮姑,你說我怎么就攤上這事【莼冢” “怎么了传透?”我有些...
    開封第一講書人閱讀 163,524評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長极颓。 經(jīng)常有香客問我朱盐,道長,這世上最難降的妖魔是什么菠隆? 我笑而不...
    開封第一講書人閱讀 58,339評(píng)論 1 293
  • 正文 為了忘掉前任兵琳,我火速辦了婚禮,結(jié)果婚禮上骇径,老公的妹妹穿的比我還像新娘躯肌。我一直安慰自己,他們只是感情好破衔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評(píng)論 6 391
  • 文/花漫 我一把揭開白布清女。 她就那樣靜靜地躺著,像睡著了一般晰筛。 火紅的嫁衣襯著肌膚如雪嫡丙。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評(píng)論 1 301
  • 那天读第,我揣著相機(jī)與錄音曙博,去河邊找鬼。 笑死卦方,一個(gè)胖子當(dāng)著我的面吹牛羊瘩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,130評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼尘吗,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼逝她!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起睬捶,我...
    開封第一講書人閱讀 38,985評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤黔宛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后擒贸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體臀晃,經(jīng)...
    沈念sama閱讀 45,420評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評(píng)論 3 334
  • 正文 我和宋清朗相戀三年介劫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了徽惋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,779評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡座韵,死狀恐怖险绘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情誉碴,我是刑警寧澤宦棺,帶...
    沈念sama閱讀 35,477評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站黔帕,受9級(jí)特大地震影響代咸,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜成黄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評(píng)論 3 328
  • 文/蒙蒙 一呐芥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奋岁,春花似錦贩耐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至虾攻,卻和暖如春铡买,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背霎箍。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評(píng)論 1 269
  • 我被黑心中介騙來泰國打工奇钞, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人漂坏。 一個(gè)月前我還...
    沈念sama閱讀 47,876評(píng)論 2 370
  • 正文 我出身青樓景埃,卻偏偏與公主長得像媒至,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子谷徙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評(píng)論 2 354