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

有帮助吗?

解决方案

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;
  }
  });

其他提示

You put the 'measuring' in the onWindowFocusChanged()-method. As the documentation states:

This is the best indicator of whether this activity is visible to the user.

You could also put it in the onResume() which is the last step before the application is completely on screen and active, however:

Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).

If the window/view has not yet been displayed there is no guarantee that it has its measurements, thus the previous method would be better.

Can you try to do this first

Log.d("Button","Button description :"+btn_show.toString());

Try printing float value as it returned by getX() and getY(). the problem might be with integer conversion. I tried your code and its working fine with me. check with your layout.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top