`

PopupWindow的使用

 
阅读更多

一个应用中不缺乏给出用户提示的对话框或者选择框,Dialog 和PopupWindow是个不错的选择。

有时需要给提示框一个进入动画和退出动画,研究了下Dialog 网上很多说使用Dialog.getWindow()。后使用

window.setWindowAnimations(int) 的方法可以实现动画效果,可惜我没成功!

 

最后使用PopupWindow代替

PopupWindow & Dialog:
  popupWindow是一个阻塞式的弹出框(在我们退出这个弹出框之前,程序会一直等待),Dialog非阻塞式弹出框(后台还可以做其他事情)

PopupWindow使用步骤总结
  Ⅰ  自定义PopupWindow布局文件,并获取获取其实例
  Ⅱ  创建PopupWindow对象,定义相关属性
  Ⅲ  PopupWindow界面显示
  Ⅳ  响应自定义布局的事件

 

1.创建进入和退出的动画

   popup_enter.xml

 popup_exit.xml

 

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="700"
        android:fromYDelta="0.0"
        android:toYDelta="-100%p" />

</set>

 

 2.动画的样式

<style name="animationPopup">
	    <item name="android:windowEnterAnimation">@anim/popup_enter</item>
	    <item name="android:windowExitAnimation">@anim/popup_exit</item>
	</style>

 

 

3.使用一个工厂模式得到 PopupWindow的实例

package com.example.slimplepopupwindow;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

public class PopupWindowFactory {
	public static PopupWindow getInsance(Context context, int resource){
		PopupWindow popupWindow = new PopupWindow(context);
		View contentView = LayoutInflater.from(context).inflate(resource, null);
		popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
		popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		// 设置popupWindow外部是否可以触摸
		popupWindow.setOutsideTouchable(true);
		popupWindow.setContentView(contentView);
		// 添加动画的样式.
                popupWindow.setAnimationStyle(R.style.animationPopup);		
		return popupWindow;
	} 
}

 4.设置PopupWindow显示的位置.

 显示在指定View 下方左边位置.

  

private void showPopupWindow(View view){
    	int[] location = new int[2];
    	view.getLocationInWindow(location);
    	if(popupWindow != null && !popupWindow.isShowing()){
    		popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, getResources().getDimensionPixelOffset(R.dimen.d5), location[1] + view.getHeight());
    	}
    }

 

 动画效果可以查看:

【android】动画效果研究
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics