android教程之使用popupwindow创建菜单示例
popupwindow是一个弹出式窗口,它可以展示任意view。他会浮在当前窗口的上方展示。
下面看代码:
public class myactivity extends activity{
private popupwindow menu;
private layoutinflater inflater;
private view layout;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
//实例化popupwindow创建菜单
initmenu();
}
//判断按键 菜单的显示与隐藏
@override
public boolean onkeydown(int keycode, keyevent event) {
if(!menu.isshowing()&&keycode == keyevent.keycode_menu){
show();
}else{
menu.dismiss();
}
if(keycode == keyevent.keycode_back&&menu.isshowing()){
menu.dismiss();
}
return true;
}
//实例化popupwindow创建菜单
private void initmenu(){
//获取layoutinflater实例
inflater = (layoutinflater) this.getsystemservice(layout_inflater_service);
//获取弹出菜单的布局
layout = inflater.inflate(r.layout.menu,null);
//设置popupwindow的布局
menu = new popupwindow(layout, windowmanager.layoutparams.wrap_content,windowmanager.layoutparams.wrap_content);
}
//显示菜单
private void show(){
//设置位置
menu.showatlocation(this.findviewbyid(r.id.main), gravity.bottom|gravity.center_horizontal,0,0); //设置在屏幕中的显示位置
}
}
菜单的布局文件:
<?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="fill_parent"
android:orientation="horizontal"
>
<imageview
android:id="@+id/icon_1"
android:background="@drawable/icon_1"
android:layout_width="40dp"
android:layout_height="40dp"/>
<imageview
android:id="@+id/icon_2"
android:background="@drawable/icon_2"
android:layout_width="40dp"
android:layout_height="40dp"/>
<imageview
android:id="@+id/icon_3"
android:background="@drawable/icon3"
android:layout_width="40dp"
android:layout_height="40dp"/>
<imageview
android:id="@+id/icon_4"
android:background="@drawable/icon4"
android:layout_width="40dp"
android:layout_height="40dp"/>
</linearlayout>
上一篇: 小程序实现留言板
下一篇: 微信小程序实现登录遮罩效果