欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

自定义对话框

程序员文章站 2022-05-31 16:49:21
...

自定义对话框

{
                Log.d("点击头像了", "点击头像了 ");
                final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                alertDialog.show();
                alertDialog.setContentView(R.layout.activity_bottom_pho);
                Window window = alertDialog.getWindow();
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
                window.setGravity(Gravity.BOTTOM);
                **自定义对话框中的控件获取要用Window。find····,实现点击事件**
                window.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
             
     



<?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="200dp"
    android:background="#00000000"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/pop_layout"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:layout_weight="1"
        android:background="#B6B5B5"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:orientation="vertical">


        <Button
            android:id="@+id/btn_take_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="20dip"
            android:background="#8e8e8e"
            android:text="拍照"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_pick_photo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="5dip"
            android:background="#8e8e8e"
            android:text="从相册选择"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dip"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="15dip"
            android:background="#8e8e8e"
            android:text="取消"
            android:textColor="#ffffff"
            android:textStyle="bold"

            />
    </LinearLayout>
</RelativeLayout>

自定义对话框

 

package com.example.my;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;
    private Button mTakePhoto, mChoosePhoto;
    private ImageView picture;
    private Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youth_go);
        final ImageView btn_head = findViewById(R.id.btn_head);
        //image_head = findViewById(R.id.image_head);


        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        btn_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("点击头像了", "点击头像了 ");
                final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                alertDialog.show();
                alertDialog.setContentView(R.layout.activity_bottom_pho);
                Window window = alertDialog.getWindow();
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
                window.setGravity(Gravity.BOTTOM);
                window.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
                //拍照
                window.findViewById(R.id.btn_take_photo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //创建file对象,用于存储拍照后的图片;
                        File outputImage = new File(getExternalCacheDir(), "output_image.jpg");

                        try {
                            if (outputImage.exists()) {
                                outputImage.delete();
                            }
                            outputImage.createNewFile();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (Build.VERSION.SDK_INT >= 24) {
                            imageUri = FileProvider.getUriForFile(MainActivity.this,
                                    "com.example.my.fileprovider", outputImage);
                        } else {
                            imageUri = Uri.fromFile(outputImage);
                        }

                        //启动相机程序
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        startActivityForResult(intent, TAKE_PHOTO);
                    }
                });
                //从相册选择照片
                window.findViewById(R.id.btn_pick_photo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            openAlbum();
                        }
                    }
                    //打开相册
                    private void openAlbum() {
                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                        intent.setType("image/*");
                        startActivityForResult(intent, CHOOSE_PHOTO);
                    }
                });



            }
        });


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("打开了保存照片", "onActivityResult: ");
        picture=findViewById(R.id.btn_head);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bm);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }break;
            case CHOOSE_PHOTO :
                if (resultCode == RESULT_OK) {
                    try{
                        if (Build.VERSION.SDK_INT >= 19) {
                            handleImageOnKitKat(data);//4.4以上版本
                        }else {
                            handleImageOnKitKat(data);//4.4以下版本
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }


    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果document类型的Uri,则通过document来处理
            String docID = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docID.split(":")[1];     //解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;

                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/piblic_downloads"), Long.valueOf(docID));

                imagePath = getImagePath(contentUri, null);

            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri,则使用普通方式使用
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的uri,直接获取路径即可
            imagePath = uri.getPath();

        }
        displayImage(imagePath);
    }
}

//            protected void onActivityResult(int requestCode,int resultCode,Intent data){
//                        switch (requestCode){
//                            case TAKE_PHOTO:
//                                if (resultCode==RESULT_OK){
//                                    try{
//                                        //将拍摄的照片显示出来
//                                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                                        picture.setImageBitmap(bitmap);
//                                    } catch (FileNotFoundException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                break;
//                            default:
//                                break;
//                        }
//                }


//    public void btn_image(View v){
//        final String[] items1={"拍照","从相册中选择","取消"};
//        final AlertDialog dialog=new AlertDialog.Builder(this)
//                .setItems(items1, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if(items1[which].equals("拍照")){
//                            File outputImage = new File(getExternalCacheDir(),
//                                    "output_image.jpg");
//                            try {
//                                if (outputImage.exists()) {
//                                    outputImage.delete();
//                                }
//                                outputImage.createNewFile();
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                            if (Build.VERSION.SDK_INT >= 24) {
//
//                                imageUri= FileProvider.getUriForFile(MainActivity.this,
//                                        "com.example.my.fileprovider",outputImage);
//                            }else {
//                                imageUri= Uri.fromFile(outputImage);
//                            }
//                            //启动相机程序
//                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//                            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
//                            startActivityForResult(intent,TAKE_PHOTO);
//                        }
//
//                      //  Toast.makeText(MainActivity.this,items1[which],Toast.LENGTH_SHORT).show();
//
//                    }
//                    protected void onActivityResult(int requestCode,int resultCode,Intent data){
//                        switch (requestCode){
//                            case TAKE_PHOTO:
//                                if (resultCode==RESULT_OK){
//                                    try{
//                                        //将拍摄的照片显示出来
//                                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//                                        picture.setImageBitmap(bitmap);
//                                    } catch (FileNotFoundException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                                break;
//                            default:
//                                break;
//                        }
//                }
//        }).create();
//        dialog.show();
//    }

## 在AndroidManifest中要注册##
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



相关标签: 自定义对话框