popupWindow 简单实现
popupWindow实现
window.xml //弹出的窗口的文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#CCCCCC" >
<Button
style="@style/menu_list"
android:background="@android:color/transparent"
android:id="@+id/food_order"
android:layout_width="fill_parent"
android:layout_height="70dp"
android:gravity="center"
android:text="@string/order"
android:onClick="joinOrder" />
</RelativeLayout>
in.xml&out.xml放在res下anim(没有的话自己创建一个)文件夹下
in.xml //显示窗口时的动作
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 定义从左向右进入的动画 -->
<translate
android:fromXDelta="-100%"
android:toXDelta="0"
android:duration="500"/>
</set>
out.xml //窗口消失时的动作
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 定义从右向左动画退出动画 -->
<translate
android:fromXDelta="0"
android:toXDelta="-100%"
android:duration="500"/>
</set>
MainActivity.java //这个不用解释
在你触发事件处理的地方加上以下代码
public void onClick(View arg0) {
// TODO Auto-generated method stub
//点一下出现再点其他地方就消失
if (null != popupWindow) {
popupWindow.dismiss();
return;
} else {
initPopuptWindow();
}
popupWindow.showAsDropDown(view); //private PopupWindow popupWindow;
}
/** 创建PopupWindow */
protected void initPopuptWindow() {
// TODO Auto-generated method stub
// 获取自定义布局文件window.xml的视图
View popupWindow_view = getLayoutInflater().inflate(R.layout.window, null,
false);
// 创建PopupWindow实例,200,70分别是宽度和高度
popupWindow = new PopupWindow(popupWindow_view, 200, 70, true);
// 设置动画效果
popupWindow.setAnimationStyle(R.style.AnimationFade);//这里就用到in.xml&out.xml了,style.xml添加样式AnimationFade
// 点击其他地方消失
popupWindow_view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
}
return;
}
});
// window.xml视图里面的控件
Button order = (Button) popupWindow_view.findViewById(R.id.food_order);
// window.xml视图里面的控件触发的事件
order.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 这里可以执行相关操作
System.out.println("打开操作");
// 对话框消失
popupWindow.dismiss();
}
});
}
<style name="AnimationFade"> <!-- PopupWindow左右弹出的效果--> <item name="android:windowEnterAnimation">@anim/in_lefttoright</item> <item name="android:windowExitAnimation">@anim/out_righttoleft</item> </style>
浙公网安备 33010602011771号