How can get x and y position of an image in androi

2019-08-09 22:46发布

问题:

I want current X & Y co ordinates of an ImageView on onCreate of Activity, is there any solution for the same ? Please share your idea on same.

回答1:

Actually, when you call setContentView() the Android nutshell starts the views drawing on surface, Which you can observe on using viewTrewwObserve So you can not get the height and width of ImageView in onCreate() as its not currently draw yet.

You can use, (Not tried)

imageView.getViewTreeObserver().addOnGlobalLayoutListener(
 new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    // Get ImageView height width here <------------
  }
});

It will Register a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

Update:

Or you can use onWindowFocusChanged (boolean hasFocus).

This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.



回答2:

(1)You can get it using the getViewTreeObserver() or (2)you can add an asynchronous Task on your onCreate()

@Override
protected void onCreate(Bundle savedInstanceState)
{
  //SIMPLY CALL YOUR ASYN TASK WITH DELAY OVER HERE LIKE THIS.

  new MyImageDrawClass().execute();
}



class MyImageDrawClass extends AsyncTask<Void, Void, Void>
{
    @Override
    protected Void doInBackground(Void... params)
    {
        try
        {
            Thread.sleep(100);
        }
        catch(InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        LayoutParams lp = mContent.getLayoutParams();
        value_wdth = mContent.getWidth();
        value_hght = mContent.getHeight();

        //PERFORM YOUR OTHER DRAWING STUFF..
        super.onPostExecute(result);
    }

}

let me know if you find issue with this, you can also reduce the time delay to Thread.sleep(10); I generally use this method to get height and to get width.