views:

487

answers:

2

So, why does this code:

package org.popoffka.apicross;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class Game extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     Button testButton = new Button(this);
     testButton.setBackgroundResource(R.drawable.cell);
     testButton.setWidth(20);
     testButton.setHeight(20);
     setContentView(testButton);
 }
}

...produce this thing: http://i42.tinypic.com/2hgdzme.png even though there's a setWidth(20) and setHeight(20) in the code? (R.drawable.cell is actually a 20x20 PNG image containing a white cell with a silver border)

+3  A: 

You are setting the button as content-view, which means you use it as the "root container".

You should add the Button to an appropriate layout, and then set the layout as content view.

Think about it, what would you have on the sides of the button? No component would cover that area, and it would be impossible for the UI to know what to render at those areas.

aioobe
Actually it would be possible to create the button and make it NOT cover the entire screen. But in this example, popoffka forgot to give his button a set of LayoutParams, which caused Android to choose default LayoutParams. The root layout of an Activity is a FrameLayout and the default layout params in a FrameLayout are FILL_PARENT/FILL_PARENT.
Romain Guy
aha. interesting. I had no idea. So basically my post is invalid?
aioobe
+1  A: 

The proper way to set the width and height of a View is to do so via the LayoutParams. See ViewGroup.LayoutParams and View.getLayoutParams().

Romain Guy