Search code examples
androidbuttoncoordinate

getX() not working for button?


I used the following method for getting x and y values of my button.It returns 0 always.What might be the problem ?

btn_show.setOnClickListener(new OnClickListener()
             {
                  @Override
                 public void onClick(View arg0) 
                 {
                       int x = (int)btn_show.getX();
                       int y=  (int)btn_show.getY();

                    Toast.makeText(getApplicationContext(), "button x is......"+x,Toast.LENGTH_SHORT ).show();
                    Toast.makeText(getApplicationContext(), "button y is......"+y,Toast.LENGTH_SHORT ).show();
     }
               });

I used this method to pass the value to another activity

Intent i = new Intent(getApplicationContext(), CustomDialogExample.class);
                    i.putExtra("value",popup_height);
                    startActivity(i);

And this method to retrieve the value

Intent i = getIntent();
         int intValue = i.getIntExtra("value", 0);

Finally this to set my popup position

Window window = customizeDialog.getWindow();
            WindowManager.LayoutParams wlp = window.getAttributes();
            wlp.y =intValue;
            window.setAttributes(wlp);

The variable intValue returns 0 always


Solution

  • Use this.

    btn_show.setOnTouchListener(new OnTouchListener() {
    
      @Override
      public boolean onTouchEvent(MotionEvent event) {
        int x = (int)event.getX();
        int y = (int)event.getY();
    
       Toast.makeText(getApplicationContext(), "button x is......"+x,Toast.LENGTH_SHORT ).show();
       Toast.makeText(getApplicationContext(), "button y is......"+y,Toast.LENGTH_SHORT ).show();
    
      return false;
      }
      });