public class PopuWindowActivty extends Activity {
private Button btnClick;
private PopupWindow popuWindow1;
private View contentView1;
private Button btn1;
private GridView gvGrid;
private int[] image = { R.mipmap.what, R.mipmap.what, R.mipmap.what,R.mipmap.what};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popu_item);
btnClick = (Button) findViewById(R.id.btn_click);
btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initPopuWindow1(v);
}
});
}
private void initPopuWindow1(View parent) {
if (popuWindow1 == null) {
LayoutInflater mLayoutInflater = LayoutInflater.from(this);
contentView1 = mLayoutInflater.inflate(R.layout.activity_main, null);
gvGrid = (GridView) contentView1.findViewById(R.id.gv_gride);
ArrayList<HashMap<String, Object>> imagelist = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < 4; i++) {
HashMap<String,Object> map=new HashMap<>();
map.put("image",image[i]);
imagelist.add(map);
}
gvGrid.setAdapter(new SimpleAdapter(PopuWindowActivty .this,imagelist,R.layout.grid_item,new String[]{"image"},new int[] {R.id.image }));
gvGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(popu.this,"I am toast",Toast.LENGTH_SHORT).show();
//点击任意gridview item,让popupwindow dismiss掉
for (int i = 0; i < 4; i++) {
if (arg2==i){
popuWindow1.dismiss();
}
}
}
});
popuWindow1 = new PopupWindow(contentView1, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
ColorDrawable cd = new ColorDrawable(0x000000);
popuWindow1.setBackgroundDrawable(cd);
//产生背景变暗效果
WindowManager.LayoutParams lp=getWindow().getAttributes();
lp.alpha = 0.4f;
getWindow().setAttributes(lp);
popuWindow1.setOutsideTouchable(true);
popuWindow1.setFocusable(true);
popuWindow1.showAtLocation((View)parent.getParent(), Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
popuWindow1.update();
popuWindow1.setOnDismissListener(new PopupWindow.OnDismissListener(){
//在dismiss中恢复透明度
public void onDismiss(){
WindowManager.LayoutParams lp=getWindow().getAttributes();
lp.alpha = 1f;
getWindow().setAttributes(lp);
}
});
}
}
//布局略…