Android view's getTop(), getLeft(), getX(), getY(), getWidth(), getHeight() methods

后端 未结 3 1778
我寻月下人不归
我寻月下人不归 2021-02-19 08:02

I am writing a drag and drop application and got really confused because of some parameters.

Please help to figure out.

First of all, I read the documentation fo

相关标签:
3条回答
  • 2021-02-19 08:25

    You can get pixels from dp with

    float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
    float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());
    

    As of the positioning question. getTop and getLeft are relative values and are based on your parent. Since the only parent of your ImageView is LinearLayout you are effectively positioning your ImageView directly below the ActionBar/ToolBar

    Also don't use an image for a circle, you can draw it easily with canvas.drawCircle it takes much less memory.

    0 讨论(0)
  • 2021-02-19 08:33

    All these measurement methods return sizes in pixels( px ), not density-pixels ( dp ). If you want to convert it you can get the density by calling:

    float density = getResources().getDisplayMetrics().density;
    

    And then divide the values you get with the provided density, for example:

    int widthDp = (int)(img.getWidth() / density);
    
    0 讨论(0)
  • 2021-02-19 08:33

    This is a supplemental answer for future visitors.

    enter image description here

    • Left, Top: When a parent view lays out a subview, left is the distance from the left side of the parent to the left side of the subview. Likewise, top is the distance from the top of the parent to the top of the subview. Thus, getLeft() and getTop() return the coordinates of the top left corner of the view relative to its parent view (not the absolute coordinates on the screen).
    • X, Y: Usually getX() and getY() will return the same thing as getLeft() and getTop(). However, sometimes it is useful to move the view a little after it has already been laid out. This can be done with setTranslationX() and setTranslationY(). If these have been set then x and y will be different from left and top, where

      x = left + translationX
      y = top + translationY
      
    • Width, Height: You can find the width and the height of the view with getWidth() and getHeight(). This is not affected by a translation.

    The above values are all in pixel dimensions.

    0 讨论(0)
提交回复
热议问题