public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private PopupWindow popupWindow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
showPopu(v);
break;
case R.id.dismiss:
popupWindow.dismiss();
setWindowAlpha(1.0f);
Toast.makeText(getApplicationContext(),"=======",Toast.LENGTH_SHORT).show();
}
}
public void showPopu(View v){
//弹出一个popuwindow
View view= LayoutInflater.from(getApplicationContext()).inflate(R.layout.popu_layout,null);
if (popupWindow==null)
popupWindow=new PopupWindow(view,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setBackgroundDrawable(getDrawable(R.color.colorAccent ));//背景设置必须要有
//auchar 锚点
//popupWindow.showAsDropDown(button,-100,100);
//popupWindow.setOutsideTouchable(true);//点击外部可以退出Popuwindow
popupWindow.setFocusable(true);//返回键可以退出popuwindow
//Log.e("=======", "onClick: "+popupWindow.isOutsideTouchable());
//popupWindow.showAsDropDown(button,-100,100, Gravity.RIGHT);
//设置动画入场和退出
popupWindow.setAnimationStyle(R.style.popuAnim);
popupWindow.showAtLocation(v,Gravity.CENTER,0,0);
setWindowAlpha(0.8f);
Button button= (Button) view.findViewById(R.id.dismiss);
button.setOnClickListener(this);
//设置窗口的消失事件
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
setWindowAlpha(1.0f);
}
});
}
public void setWindowAlpha(float alpha){
WindowManager.LayoutParams params=getWindow().getAttributes();//不能new windows
params.alpha=alpha;
getWindow().setAttributes(params);
}
}
popupWindow使用示例
最新推荐文章于 2020-09-15 11:17:42 发布