使用PopupWindow
简单介绍
当我们点击应用列表里的条目时, 会弹出一个小窗口,这种小窗口叫做PopupWindow.
大致看一下这个类及其方法, 它有些方法和View有点像,有些又和Dialog比较像.
它也是通过Window加到屏幕上的,但是它和Dialog的又不太一样,它的弹出位置不固定.
基本用法, 创建一个Demo
public void popup(View v) {
TextView contentView = new TextView(getApplicationContext());
contentView.setTextColor(Color.RED);
contentView.setText("我是一个弹出窗口");
int width = ViewGroup.LayoutParams.WRAP_CONTENT;
int height = ViewGroup.LayoutParams.WRAP_CONTENT;
// 弹出窗口,第一个参数表示里面要显示的View,后两个表示宽高.
PopupWindow popupWindow = new PopupWindow(contentView, width, height);
// 如果想让一个弹出窗能够在点击别的区域时或者按返回键时消失,需要调用下面两个方法
// 表示可以获取焦点
popupWindow.setFocusable(true);
// 必须设置背景,如果实在不想要,可以设置new ColorDrawable(Color.TRANSPARENT)
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GREEN));
// 显示在某个View的左下角
popupWindow.showAsDropDown(mTv);
// 显示在屏幕的某个地方,第一个参数只需要传当前Activity里任何一个View就行.
popupWindow.showAtLocation(mTv, Gravity.CENTER, 0, 0);
// 显示在某个View的左下角,并且指定x, y轴的偏移量
popupWindow.showAsDropDown(mTv, mTv.getWidth(), -mTv.getHeight());
}
// 设置弹出动画
mPopupWindow.setAnimationStyle(R.style.PopupAnimation);
<!-- PopupWindow 动画 -->
<style name="PopupAnimation">
<item name="android:windowEnterAnimation">@anim/popup_enter</item>
<item name="android:windowExitAnimation">@anim/popup_exit</item>
</style>
popup_enter
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="30%" android:toXDelta="0"
android:interpolator="@interpolator/overshoot"
android:duration="200"/>
<alpha android:fromAlpha="0.5" android:toAlpha="1.0"
android:interpolator="@interpolator/decelerate_cubic"
android:duration="200" />
</set>
popup_exit
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate android:fromXDelta="0" android:toXDelta="30%"
android:interpolator="@interpolator/anticipate"
android:duration="200"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:interpolator="@interpolator/accelerate_cubic"
android:duration="200"/>
</set>
interpolator:
overshoot
<?xml version="1.0" encoding="utf-8"?>
<overshootInterpolator xmlns:android="http://schemas.android.com/apk/res/android" />
decelerate_cubic
<?xml version="1.0" encoding="utf-8"?>
<accelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:factor="1.5" />
anticipate
<?xml version="1.0" encoding="utf-8"?>
<anticipateInterpolator xmlns:android="http://schemas.android.com/apk/res/android" />
accelerate_cublic
<?xml version="1.0" encoding="utf-8"?>
<accelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:factor="1.5" />