package mobile.android.ch06.custom.menu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.PopupWindow;
import android.widget.Toast;
public class Main extends Activity
{
private PopupWindow pop;
private View layout;
/**表示弹出菜单是否出现。1:打开状态,2:不显示状态*/
private int state = 2;//关闭状态
public static final int OPENED=1;
public static final int CLOSED=2;
Display display=null;//获取屏幕尺寸
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display=getWindowManager().getDefaultDisplay();//获取屏幕尺寸
}
@Override//当有键按下的时候
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_MENU:
if (state == OPENED)return false;//如果弹出窗口处于活动状态,则再按菜单无效
//得到菜单布局对象
layout = getLayoutInflater().inflate(R.layout.menu_layout, null);
//制作弹出菜单
pop = new PopupWindow(layout,display.getWidth(),display.getHeight());
//设置layout在PopupWindow中显示的位置
pop.showAtLocation(layout, Gravity.BOTTOM, 0, 0);
View home = layout.findViewById(R.id.home);//获取一个菜单
home.setOnClickListener(new OnClickListener()//为这个菜单设置点击事件
{
@Override
public void onClick(View view)
{
Toast.makeText(Main.this, "单击定制菜单.", Toast.LENGTH_LONG).show();
pop.dismiss();//关闭弹出窗口
state = CLOSED;//弹出窗口处于关闭状态
}
});
state = OPENED;
return false;
//如果菜单处于打开状态,则关闭弹出菜单;如果菜单没有出来,直接关闭应用程序。
case KeyEvent.KEYCODE_BACK:
if (state == OPENED)
{
pop.dismiss();
state = CLOSED;
}
else if (state == CLOSED)
{
finish();
}
return false;
}
return super.onKeyDown(keyCode, event);
}
}