2018-06-05-PopupWindow

PopupWindow

Android的对话框有两种:PopupWindow和AlertDialog。他们的不同点在于:AlertDialog位置固定,但是PopWindow位置随意

PopWindow的位置按照有无偏移,可以分为偏移和无偏移两种
按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。
具体如下:

showAsDropDown(View ancher):相对于某个空间的位置(正左下方),无偏移
showAsDropDown(View anchor,int xoff,int yoff):相对于控件的位置有偏移
showAtLocation(View parent, int gravity, int x,inty):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BUTTOM等),可以设置便宜或者无偏移

/**
 * PopupWindow
 */
public class MainActivity extends AppCompatActivity {

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

    }

    public void  showWindow(View v){

        View view = getLayoutInflater().inflate(R.layout.popupwindow,null);

        //实例化创建PopupWindow对象(窗体的视图,宽,高)
        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.alert_dark_frame));
        
        //PopWindow的各种功能
        popupWindow.getBackground().setAlpha(100);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED);
        popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);

        popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);

        //获取屏幕尺寸
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
    }
}

你可能感兴趣的:(2018-06-05-PopupWindow)