如何在屏幕上获取按钮的左,右角位置?

时间:2018-07-05 07:36:00

标签: android dialog

我试图获取视图位置(右上角位置和左下角位置),并在视图的右侧或左侧显示自定义对话框,但是我没有获得确切的视图位置。这是我的代码

    int x=view.getLeft()+  (view.getHeight()*4);
    int y= view.getBottom()+(view.getWidth()*2);
    showDialog(x,y,Gravity.TOP,Gravity.LEFT);`  

    public void showDialog(int x, int y,int gravity_y,int gravity_x){
    final Dialog dialog  = new Dialog(this, R.style.ActivityDialog);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
    dialog.setContentView(R.layout.cofirm_sell);
    dialog.setCanceledOnTouchOutside(false);
    WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
    dialog.getWindow().getAttributes().windowAnimations=R.style.DialogTheme;
    wmlp.gravity = gravity_y | gravity_x;
    wmlp.x = x;
    wmlp.y = y;
    ImageButton close=(ImageButton)dialog.findViewById(R.id.close);
    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();

}

我想要这个

enter image description here

3 个答案:

答案 0 :(得分:1)

检查:

    int[] outLocation = new int[2];
    view.getLocationOnScreen(outLocation);
    Rect rect = new Rect(
            outLocation[0],
            outLocation[1],
            outLocation[0] + view.getWidth(),
            outLocation[1] + view.getHeight());
    //right upper corner rect.right,rect.top 
    //left bottom corner rect.left,rect.bottom

答案 1 :(得分:0)

尝试

int[] location = new int[2];
view.getLocationOnScreen(location);
int x1=location[0]-(view.getWidth());
int y1= location[1]-(view.getHeight());

答案 2 :(得分:0)

感谢@Sree,在Kotlin:

val location = IntArray(2)
view.getLocationInWindow(location)

val left = location[0]
val right = left + view.width
val top = location[1]
val bottom = top + view.height