先来张效果图:
关于Android PopupWindow,
1.是悬浮在所有控件之上的;
2.PopupWindow不能放在layout的xml中,只能new出来;
3.showAtLocation或者showAsDropDown函数,好像不能在onCreate中调用,一般都是点击某个按钮才调用;
上代码
一、Java代码
private HashMap<String,Object> map;
private ArrayList<HashMap<String,Object>> list;
private PopupWindow popupTaskMenu; // 新建任务菜单
private ListView listTaskMenu; // 新建任务的PopupWindow的内部的ListView
。。。。。
// 初始化PopupWindow,在onCreate中。初始化完成后,在其它地方就可以调用show来显示了
private void createPopupMenu(){
// 把xml转化为View,准备设置为PopupWind的Content
View viewTaskMenu = LayoutInflater.from(this).inflate(R.layout.task_menu, null);
// 找到PopupWindow内部的ListView
listTaskMenu = (ListView) viewTaskMenu.findViewById(R.id.list_task);
// 为ListView准备适配器的HashMap
list = new ArrayList<HashMap<String,Object>>();
for(int i = 0;i<ConfigStrs.length;i++){
map = new HashMap<String,Object>();
map.put("name", ConfigStrs[i]);
// map.put("icon", IconRes[i]);
list.add(map);
}
// 构造适配器
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.task_listview_item,
new String[]{"name"},
new int[]{R.id.txt_task_info});
listTaskMenu.setAdapter(adapter);
// 把包含设置好了的ListView的layout.task_menu.xml转换的View放到PopupWindow中
// 四个参数:1.上面所说的View,2.PopupWindow宽度,3.PopupWindow高度,4.是否获得焦点
popupTaskMenu = new PopupWindow(viewTaskMenu, 400, 500, true);
// 设置动画
popupTaskMenu.setAnimationStyle(R.style.Animation_MenuBottomFadeIn);
// 响应返回键必须的语句
popupTaskMenu.setBackgroundDrawable(new BitmapDrawable());
}
。。。。
// 显示PopupWindow,相当于对话框的show函数。
// 四个参数:1.可以随便找个本Activity的setContentView里的layout的一个控件的View,2.对齐方式,和第一个参数似乎没什么关系,是相对于屏幕的布局方式,
3.在对齐方式确定的远点坐标的基础上,x轴偏移,4.y轴便宜
popupTaskMenu.showAtLocation(findViewById(R.id.rlt_task_config), Gravity.CENTER|Gravity.BOTTOM, 0, 120);
。。。。
// 关闭PopupWindow
popupTaskMenu.dismiss();
二、资源文件
(1).task_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/task_menu_bg"
android:orientation="vertical" >
<ListView
android:id="@+id/list_task"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:divider="@drawable/list_divider_line" />
</LinearLayout>
(2).task_listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/txt_task_info"
android:layout_width="fill_parent"
android:layout_height="35.0dip"
android:gravity="left|center"
android:paddingLeft="28.0dip"
android:textColor="@color/black_color"
android:textSize="15sp" />
</RelativeLayout>
问题:
1.返回按钮不能dismiss掉PopupWindow的原因?
答:少一行代码,popupTaskMenu.setBackgroundDrawable(new BitmapDrawable());
可以参考http://blog.csdn.net/simayilong/article/details/6696765