Android ignoring my setWidth() and setHeight()
Asked Answered
P

3

4

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)

Peroxidize answered 4/5, 2010 at 12:46 Comment(0)
G
13

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

Glim answered 4/5, 2010 at 16:36 Comment(0)
H
3

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.

Holstein answered 4/5, 2010 at 12:50 Comment(2)
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.Glim
aha. interesting. I had no idea. So basically my post is invalid?Holstein
F
0

I know this is a late answer but hope it helps someone.

That is because the Button has a minimum width of 64dip by default. Set it to 0 before setting the width.

b.setMinimumWidth(0);

Otherwise best practice is to use LayoutParams

Faison answered 10/9, 2015 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.