1

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.

Hiren Patel
  • 48,538
  • 20
  • 161
  • 144
  • in onCreate there is no display measured yet. you cannot (unless you explicitely measure your layout) – njzk2 Feb 05 '13 at 11:54

2 Answers2

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.

user370305
  • 103,719
  • 23
  • 157
  • 149
0

(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.

Anuj
  • 1,985
  • 21
  • 21
  • This is a complete hack. Thread.sleep() is used far too often, usually for bad things. This is a bad thing. Artificially creating a delay in the "hope" that the layout completes in time. Yeuch. – Simon Feb 05 '13 at 13:14
  • your right about it, but i have already mentioned the `"1)You can get it using the getViewTreeObserver()"` and this was just another solution if he wishes to achieve it that way, the hack seems to work just fine for me. – Anuj Feb 05 '13 at 13:20