0

I am trying to get the location of textView using the getX() and getY() functions.

As seen from the code below, textView.getX() and textView.getY() used in onCreate() method returns a value 0.0.

But textView.getX() and textView.getY() used in checkCoord returns 32.0 for both getX and getY functions.

I am unable to understand this change in values for getX() and getY(). Kindly help. Code is as shown below:

public class MainActivity extends Activity {
        TextView textView;
        Button bt;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

                   textView = (TextView) findViewById(R.id.textView1);

                   bt = (Button) findViewById(R.id.button1);

                   System.out.println("Inside onCreate textView X : " + textView.getX());
                   System.out.println("Inside onCreate textView Y : " + textView.getY());

                   bt.setOnClickListener(new View.OnClickListener() {

                   @Override
                   public void onClick(View v) {
                   // TODO Auto-generated method stub
                   checkCoord(v);

                   }
                   });

       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
       }

       public void checkCoord(View view) {

            System.out.println("Inside checkCoord textView X : " + textView.getX());
            System.out.println("Inside checkCoord textView Y : " + textView.getY());

       }

}
flx
  • 14,146
  • 11
  • 55
  • 70
sujith
  • 1
  • 1

1 Answers1

1

The difference has to do with the lifecycle of the activity see here:

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Basically in onCreate your view hasn't actually been drawn on the screen yet so there are no values to return. But when you call the method through the onClickListener the view has been drawn so there are values to return

Mobius
  • 153
  • 8