android popupwindow UI進階之彈窗的使用
}
if (mPop.isShowing()) {
mPop.dismiss();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button)findViewById(R.id.bt1);
bt2 = (Button)findViewById(R.id.bt2);
bt3 = (Button)findViewById(R.id.bt3);
bt4 = (Button)findViewById(R.id.bt4);
bt5 = (Button)findViewById(R.id.bt5);
layout = View.inflate(this, R.layout.window, null);
gv = (GridView) layout.findViewById(R.id.gv);
MyAdapter adapter=new MyAdapter(this,items,icons);
gv.setAdapter(adapter);
bt1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
initPopWindow();
mPop.showAsDropDown(v);//以這個Button為anchor(可以理解為錨,基準),在下方彈出
}});
bt2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
initPopWindow();
mPop.showAsDropDown(v,20,-20);//橫軸偏移20,縱軸-20,一個狀態(tài)欄的長度
}});
bt3.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
initPopWindow();
mPop.showAtLocation(PopWindow.this.findViewById(R.id.rl),
Gravity.CENTER, 0, 0);//在屏幕居中,無偏移
}});
bt4.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
initPopWindow();
mPop.showAtLocation(PopWindow.this.findViewById(R.id.rl),
Gravity.TOP | Gravity.LEFT, 20, 20);//在屏幕頂部|居右,帶偏移
}});
bt5.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (mPop != null) {
mPop.dismiss();
}
}});
}
public boolean onKeyDown(int keyCode, KeyEvent event){
//截獲按鍵事件
if(keyCode == KeyEvent.KEYCODE_MENU){
initPopWindow();
mPop.showAtLocation(this.findViewById(R.id.rl),
Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //在屏幕底部
}else if(keyCode == KeyEvent.KEYCODE_BACK){
if(mPop.isShowing()){
mPop.dismiss();
}else{
System.exit(0);
}
}
return false;
}
}
只有一個GridView。main.xml就不貼了,就幾個Button。
當然彈窗的作用不僅限于menu,你還可以用他做的更多來為你UI增色。
評論