Activity设置为对话框属性时(Theme.Dialog)时,改变其在屏幕中的位置

原帖http://stackoverflow.com/questions/2163427/android-dialog-activity-position

如果有需要要将Activity变成一个窗口形式(在Manifest.xml中的activity标签设置android:theme="@android:style/Theme.Dialog" 属性),默认Activity窗口弹出是在屏幕的正中央。通过覆写Activity中onAttachedToWindow()方法,在期中将DecorView的参数重设一下就可以指定其显示的位置了。

@Override

public void onAttachedToWindow() {

    super.onAttachedToWindow();



    View view = getWindow().getDecorView();

    WindowManager.LayoutParams lp = (WindowManager.LayoutParams) view.getLayoutParams();

    lp.gravity = Gravity.LEFT | Gravity.TOP;

    lp.x = 10;

    lp.y = 10;

    lp.width = 300;

    lp.height = 300;

    getWindowManager().updateViewLayout(view, lp);

}

lp.x , lp.y , lp.width ,lp.height的具体值可以定义到res/values/dimens.xml中,方便以后修改。

@Override

    public void onAttachedToWindow() {

        // 设置本Activity在父窗口的位置

        super.onAttachedToWindow();

        View view = getWindow().getDecorView();

        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) view

                .getLayoutParams();

        lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;

        lp.x = getResources().getDimensionPixelSize(

                R.dimen.playqueue_dialog_marginright);

        lp.y = getResources().getDimensionPixelSize(

                R.dimen.playqueue_dialog_marginbottom);

        lp.width = getResources().getDimensionPixelSize(

                R.dimen.playqueue_dialog_width);

        lp.height = getResources().getDimensionPixelSize(

                R.dimen.playqueue_dialog_height);

        getWindowManager().updateViewLayout(view, lp);

    }
 <resources>

 <dimen name="playqueue_dialog_marginright">0dp</dimen>

    <dimen name="playqueue_dialog_marginbottom">60dp</dimen>

    <dimen name="playqueue_dialog_width">250dp</dimen>

    <dimen name="playqueue_dialog_height">380dp</dimen>

    <dimen name="playqueue_dialog_select_item_from_top">90dp</dimen>

</resources>

 

 

 

 

你可能感兴趣的:(Activity)