android 对话弹出框(Dialog AlertDialog PopupWindow)

一直认为动手是学习的最好的方法。。。

本篇文章主要讲述Dialog AlertDailog PopupWindow

一:Dialog

1:直接弹出框

先看布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:id="@+id/dialog_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="5dp"
        android:text="标题"
        android:textSize="18sp"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#DEDEDE"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" 在今年年初时,习近平曾发出经典一叹“时间都去哪儿了”,自己给出的答案是主要都用在工作上了"/>
    </LinearLayout>
    
    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#DEDEDE"/>
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:id="@+id/ensure"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="5dp"
            android:gravity="center"
            android:text="确定"/>
        <View
            android:layout_width="1px"
            android:layout_height="match_parent"
            android:background="#DEDEDE"/>
        <TextView 
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:padding="5dp"
            android:gravity="center"
            android:text="取消"/>
    </LinearLayout>

</LinearLayout>

dialog主体部分:

private void dialog(){
       final Dialog dialog = new Dialog(this);
       //设置Dialog没有标题,这个一定要在设置内容之前定义
       dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
       dialog.setContentView(R.layout.dialog_item);
       Window window = dialog.getWindow();
       //用这个弹出框才能正确显示
       window.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
       //设置开始 结束动画
       window.setWindowAnimations(R.style.DialogAnimation);
		
        WindowManager m = getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        m.getDefaultDisplay().getMetrics(dm);
        //getAttributes 获得属性设置
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.LEFT | Gravity.TOP);
        //通过WindowManager.LayoutParams.x与WindowManager.LayoutParams.y设置的是对话框相对于屏幕中间位置的偏移量,
        //并不是屏幕的绝对位置。
        lp.x = (int) (dm.widthPixels * 1);
        lp.y = (int) (dm.heightPixels * 0.3);
        lp.alpha = 1.0f; // 透明度0:完全透明 1: 完全不透明
        window.setAttributes(lp);
		
		 /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
//        WindowManager m = getWindowManager();
//        DisplayMetrics dm = new DisplayMetrics();
//        m.getDefaultDisplay().getMetrics(dm);
//        //Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (dm.widthPixels * 0.6); // 高度设置为屏幕的0.6
//        p.width = (int) (dm.heightPixels * 0.6); // 宽度设置为屏幕的0.65
//        window.setAttributes(p);
		
		TextView ensure = (TextView) dialog.findViewById(R.id.ensure);
		TextView cancel = (TextView) dialog.findViewById(R.id.cancel);
		
		ensure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		
		cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		//点击控件之外 对话框消失
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

new Dialog(this);当然也可以添加style  new Dialog(this, R.style.style名字);

dialog用setContentView()方法添加自己对话的布局 这样就可以自己定制自己需要的弹出框样式

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) 弹出框有个默认的标题 用这个方法可以去掉 当然也可以在style文件中

用<item name="android:windowNoTitle">true</item>来去掉

弹出框也就是一个窗口,可以用dialog.getWindow()获得这个窗口,然后就可以像对窗口设置属性一样,对弹出框设置一些需要的属性

window.setGravity():设置弹出框的位置 Gravity.BOTTOM Gravity.TOP Gravity.LEFT Gravity.RIGHT;

window.setLayout():设置布局相对于窗口的位置  一定要设置 不然自定义的布局会显示不完全LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT

window.setWindowAnimations():设置弹出框开始结束动画 用style文件

style文件:

<style name="DialogAnimation" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/dialog_enter_animation</item>
        <item name="android:windowExitAnimation">@anim/dialog_exit_animation</item>
</style>

dialog_enter_animation:

<?xml version="1.0" encoding="utf-8"?>
<!-- 弹出时动画 -->  
<set xmlns:android="http://schemas.android.com/apk/res/android">  
    <scale   
        android:interpolator="@android:anim/accelerate_interpolator"  
        android:fromXScale="0.7"  
        android:toXScale="1.0"  
        android:fromYScale="0.7"  
        android:toYScale="1.0"  
        android:pivotX="50%"  
        android:pivotY="50%"  
        android:fillAfter="false"  
        android:duration="200"/>  
</set>  

dialog_exit_animation:

<?xml version="1.0" encoding="utf-8"?>
<!-- 退出时动画效果 -->  
<set xmlns:android="http://schemas.android.com/apk/res/android">  
<!--     <scale    -->
<!--         android:interpolator="@android:anim/accelerate_interpolator"   -->
<!--         android:fromXScale="0.5"   -->
<!--         android:toXScale="1.0"   -->
<!--         android:fromYScale="0.5"   -->
<!--         android:toYScale="1.0"   -->
<!--         android:pivotX="50%"   -->
<!--         android:pivotY="50%"   -->
<!--         android:fillAfter="false"   -->
<!--         android:duration="200"/>   -->
</set>  

在这里我把退出设置成无

既然是窗口啦 ,当然就可以用WindowManager.LayoutParams来设置一些属性啦

而且要记住 dialog.show()是一定要调用的 show来启动弹出框


2:底部弹出框

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >
    <!-- 顶级这个LinearLayout 不能加background 不然设置不了透明 不明白 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/dialog_bottom_bg"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/takePhotos"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                android:text="打开照相机"
                android:textColor="#400099"
                android:textSize="18sp" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:background="#DEDEDE" />

        <LinearLayout
             android:id="@+id/photos"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                android:text="从手机相册获取"
                android:textColor="#400099"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@drawable/dialog_bottom_bg"
        android:orientation="vertical"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="取消"
            android:textColor="#400099"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

主体部分:

	private void bottomDialog(){
		final Dialog dialog = new Dialog(this, R.style.Translucent_NoTitle);
		//设置Dialog没有标题,这个一定要在设置内容之前定义
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_bottom);
		
		Window window = dialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		
		window.setWindowAnimations(R.style.DialogBottom);
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		
//		WindowManager.LayoutParams params = window.getAttributes();
//		params.alpha = 0.5f;
//		window.setAttributes(params);
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		
		LinearLayout takePhotos = (LinearLayout) dialog.findViewById(R.id.takePhotos);
		LinearLayout photos = (LinearLayout) dialog.findViewById(R.id.photos);
		LinearLayout cancel = (LinearLayout) dialog.findViewById(R.id.cancel);
		
		takePhotos.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		
		photos.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		
		cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
	}

dialog style:

    <style name="dialog_style_bottom" parent="@android:Theme.Dialog">
        <item name="android:windowFrame">@null</item>边框
        <item name="android:windowIsFloating">true</item>是否浮现在activity之上
        <item name="android:windowIsTranslucent">false</item>半透明
        <item name="android:windowNoTitle">true</item>无标题
        <item name="android:windowBackground">@color/transparent</item>背景透明 :设置dialog的背景
        <item name="android:backgroundDimEnabled">true</item>模糊 dialog的背景是否昏暗 是否模糊显示
        <item name="android:background">@android:color/transparent</item> 
    </style>

android:background 一定要设置的 不然 背景会出现黑色边框

二:AlertDialog

alertDialog用法很简单 但是感觉样式不太好看 虽说有setView添加布局 但感觉不太好用(又可能是自己学还不太够)

直接上代码 (讲解也代码中):

@SuppressLint("NewApi")
	private void alertDialog(){
		/* 
		 * setTitle :为对话框设置标题
         * setIcon :为对话框设置图标
         * setMessage:为对话框设置内容
         * setView : 给对话框设置自定义样式
         * setItems :设置对话框要显示的一个list,一般用于显示几个命令时
         * setMultiChoiceItems :用来设置对话框显示一系列的复选框
         * setNeutralButton    :普通按钮
         * setPositiveButton   :给对话框添加"Yes"按钮
         * setNegativeButton :对话框添加"No"按钮
         */
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("你好");
		dialog.setMessage("你们一切都还好吗");
//		View view = LayoutInflater.from(this).inflate(R.layout.alertdialog, null);
//		dialog.setView(view);
		/* 只是在android的alertDialog中封装好的一些Button 这些Button和普通的Button没有任何区别,
		 * 可以写任意的方法,只是命名上的不同,一般有三个Button:PositiveButton,NegativeButton,NeutralButton。
		 * 从名字可以看的出来,代表确定,否定,和中立,其实三个Button可以写你任意的方法,只是位置上的不同而已,确定Button一般靠左,这是阅读习惯。
		 * 本质上都是三个Button并没有很大的区别,且setPositiveButton和setNeutralButton都自带有dismiss效果
		 */
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		dialog.show();
	}

三:PopupWindow

弹出框 用于平常除了对话框的一些弹框 比如微信中”+“ 点击弹出的那个框

首先添加布局文件

                View view = LayoutInflater.from(this).inflate(R.layout.listview_pop, null);
		btn_pop_close = (ImageView) view.findViewById(R.id.btn_pop_close);
		
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupWindow.setBackgroundDrawable(new ColorDrawable());
		popupWindow.setAnimationStyle(R.style.pop);

setAnimationStyle():添加弹出动画

style文件:

    <style name="pop">
        <item name="android:windowEnterAnimation">@anim/slide_in</item>
        <item name="android:windowExitAnimation">@anim/slide_out</item>
    </style>

slide_in:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    
    <translate android:duration="300" android:fromXDelta="100%p" android:toXDelta="0%"/>

</set>

slide_out:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    
    <translate android:duration="300" android:fromXDelta="0%" android:toXDelta="100%p"/>

</set>

启动代码(里面有详细的讲解):

private void pop(){
		int[] coord = new int[2];
		imageButton.getLocationInWindow(coord);
		/* showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
		 * showAsDropDown(View anchor, int xoff, int yoff):相对当前控件(anchor)的位置,有偏移
		 * showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),
		 * 可以设置偏移或无偏移
		 */
		//设置popwindow显示位置
//		popupWindow.showAsDropDown(imageButton, 100, 100);
		popupWindow.showAtLocation(imageButton, Gravity.TOP, coord[0], coord[1]);
		//获取popwindow焦点 设置了焦点,那么这个弹出窗体是当前操作的窗口默认是false,为false时,PopupWindow没有获得焦点能力,
		//如果这是PopupWindow的内容中有EidtText,需要输入,这是是无法输入的;只有为true的时候,PopupWindow才具有获得焦点能力,EditText才是真正的EditText。
		popupWindow.setFocusable(true);
		//设置popwindow如果点击外面区域,便关闭。这个需要和setBackgroundDrawable(new ColorDrawable())结合才可以
		popupWindow.setOutsideTouchable(true);
		//解决第一次点击不消失的问题
		popupWindow.update();
	}


上面讲的项目代码:点击下载


持续更新ing MMjiajia132

你可能感兴趣的:(android 对话弹出框(Dialog AlertDialog PopupWindow))