自定义 PopupWindow

2017-04-17  本文已影响72人  涛涛123759

MainActivity:

private PopupWindow popupWindow;
private View popupWindow_view;
private TextView but_back, but_stolen, but_cogradient, but_recover;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    popupWindow_view = getLayoutInflater().inflate(R.layout.layout_rg_delcheck, null, false);
    but_back = (TextView) popupWindow_view.findViewById(R.id.tv_back);
    but_back.setOnClickListener(this);
    but_stolen = (TextView) popupWindow_view.findViewById(R.id.tv_stolen);
    but_stolen.setOnClickListener(this);
    but_cogradient = (TextView) popupWindow_view.findViewById(R.id.tv_cogradient);
    but_cogradient.setOnClickListener(this);
    but_recover = (TextView) popupWindow_view.findViewById(R.id.tv_recover);
    but_recover.setOnClickListener(this);



    findViewById(R.id.imagr_view).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPopupWindow(v);
        }
    });


}





public void showPopupWindow(View view) {
    // 创建PopupWindow实例,300,LayoutParams.MATCH_PARENT分别是宽度和高度
    popupWindow = new PopupWindow(popupWindow_view, 300, ViewGroup.LayoutParams.MATCH_PARENT, true);
    // 如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框(必须设置)
    popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.mainmenubottom1));
    popupWindow.setOutsideTouchable(true);
    popupWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画
    popupWindow.setTouchable(true);
    popupWindow.setFocusable(true);
    //设置popupWindow显示的位置,参数依次是参照View,x轴的偏移量,y轴的偏移量
    popupWindow.showAsDropDown(view, 0, 15);
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.alpha = 0.7f;
    getWindow().setAttributes(lp);
    // 弹出菜单栏背景变暗
    popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 1f;
            getWindow().setAttributes(lp);
        }
    });

}

动画文件:anim_pop.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="2000">
    </alpha>
</set> 
上一篇下一篇

猜你喜欢

热点阅读