自定义popupwindow二三事

效果图:

自定义popupwindow二三事_第1张图片

代码:

public class ViewActivity extends Activity implements View.OnClickListener {

    PopupWindow popWindow;
    LinearLayout rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);

        rootView = (LinearLayout) findViewById(R.id.ll_rootview);

        initPopWindow(this);
    }

    @Override
    public void onClick(View v) {
        popWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }

    public void initPopWindow(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.view_share, null);
        popWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);

        ImageView iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });

        //给popupwindow设置返回键监听
        popWindow.getContentView().setFocusableInTouchMode(true);
        popWindow.getContentView().setFocusable(true);
        popWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    if (popWindow != null && popWindow.isShowing()) {
                        popWindow.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
    }
}

背景是否为灰色:

//直接在view_share的根布局设置背景颜色就可以
  android:background="#aa666666"

你可能感兴趣的:(自定义,popup,弹窗)