標籤:android style class blog code java
PopupWindow可以實現浮層效果,而且可以自訂顯示位置,出現和退出時的動畫。
首先解析一個View
LayoutInflater inflater = getLayoutInflater();final View view = inflater.inflate(R.layout.popup, null);
建立PopupWindow 構造參數 PopupWindow(View contentView, int width, int height, boolean focusable)。
contentView為要顯示的view,width和height為寬和高,值為像素值,也可以是MATCHT_PARENT和WRAP_CONTENT。
focusable為是否可以獲得焦點,這是一個很重要的參數。
這裡需要為popupWindow設定一個背景,點擊其他地區才能讓PopupWindow消失。
PopupWindow popupWindow = new PopupWindow(view, 400, 400, true);popupWindow.setBackgroundDrawable(new BitmapDrawable());
顯示PopupWindow
showAsDropDown(View anchor)://相對某個控制項的位置(正左下方),無位移showAsDropDown(View anchor, int xoff, int yoff)://相對某個控制項的位置,有位移showAtLocation(View parent, int gravity, int x, int y)://相對於父控制項的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設定位移或無位移
為PopupWindow指定動畫
PopupWindow出現時的動畫,popup_enter.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:fromXScale="1.0" android:toXScale="1.0" android:fromYScale="0" android:toYScale="1.0" android:pivotX="50%" android:pivotY="0%" android:duration="100" /> </set>
PopupWindow消失時的動畫,popup_exit.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:fromXScale="1.0" android:toXScale="1.0" android:fromYScale="1.0" android:toYScale="0" android:pivotX="50%" android:pivotY="0%" android:duration="50" /> </set>
再設定動畫的style
<style name="PopupAnimation" parent="android:Animation"> <item name="android:windowEnterAnimation">@anim/popup_enter</item> <item name="android:windowExitAnimation">@anim/popup_exit</item></style>
最後通過Java代碼設定動畫
popupWindow.setAnimationStyle(R.style.PopupAnimation);
另外在記錄一個從螢幕底部彈出的動畫
menu_bottombar_in.xml
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="250" android:fromYDelta="100.0%" android:toYDelta="0.0" /></set>
menu_bottombar_out.xml
<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="250" android:fromYDelta="0.0" android:toYDelta="100%" /></set>
定義樣式
<style name="anim_menu_bottombar"> <item name="android:windowEnterAnimation">@anim/menu_bottombar_in</item> <item name="android:windowExitAnimation">@anim/menu_bottombar_out</item></style>
最後顯示showAtLocation(findViewById(R.id.layout_main), Gravity.BOTTOM, 0, 0);