tags:

views:

38

answers:

1

I have a button whose dimensions I do not touch (and which displays correctly on screen). However, when I request its dimensions they come in at 0x0. So, I'm assuming that at the time I'm asking, they button hasn't been considered.

My code is as follows:

public void onCreate(Bundle savedInstanceState) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    int screenWidth = metrics.widthPixels / 2;


    super.onCreate(savedInstanceState);
     setContentView(R.layout.get_started);

    Button myButton = (Button) findViewById(R.id.startButton);



    int l = screenWidth/2 - myButton.getWidth() / 2;
    int t = 600;
    int r = l + myButton.getWidth(); 
    int b = t + myButton.getHeight();

    myButton.layout(l, t, r, b);
    myButton.forceLayout();


    Context context = getApplicationContext();
    CharSequence text = "My Button is " + myButton.getWidth() + " wide and " + myButton.getHeight() + " tall";
    int duration = Toast.LENGTH_LONG;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();

}

Note that my ultimate intention is to put it 600pixels from the top and centered on the screen (this isn't happening either, it just sits in the top left corner of the screen.

I'm using an AbsoluteLayout but not assigning any specific position to the button in the XML.

Just starting out in Android, so, please don't flame... I searched for a while before resorting to asking :)

+1  A: 

This document on how android draws views might be helpful to you.

You are correct in thinking that in onCreate, your button doesn't yet have a size.

As to what you are attempting.. AbsoluteLayout is depricated, you most likely don't want to be using it.

Also, you should not set view locations based on pixel values, since different phone screens have different number of pixels. If you really want absolute values, use dip (density independent pixels) as the units, see supporting multiple screen sizes.

Mayra