NadeMaster
NadeMaster

Reputation: 1

Android create four buttons with even weight distribution programmatically

I am having major issues getting my program to properly display 4 buttons, side by side, with the same width. I have tried a bunch of combinations, and spent over an hour on StackOverflow searching solutions, with no luck on any of them. How can I go about making these four buttons all with the same height in the same row on a vertical interface?

This is what I have so far with no luck. Either buttons too large, too small, or are hidden since width 0.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        layout.setWeightSum(1);

        Button redButton = new Button(this);
        redButton.setText("Red");
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                0,
                LayoutParams.WRAP_CONTENT, 
                0.25f);
        redButton.setWidth(0);
        redButton.setLayoutParams(p);
        layout.addView(redButton);

        Button greenButton = new Button(this);
        greenButton.setText("Green");
        greenButton.setLayoutParams(p);
        greenButton.setWidth(0);
        layout.addView(greenButton);

        Button blueButton = new Button(this);
        blueButton.setText("Blue");
        blueButton.setLayoutParams(p);
        blueButton.setWidth(0);
        layout.addView(blueButton);

        Button yellowButton = new Button(this);
        yellowButton.setText("Yellow");
        yellowButton.setLayoutParams(p);
        yellowButton.setWidth(0);
        layout.addView(yellowButton);

        setContentView(layout);
    }

Upvotes: 0

Views: 424

Answers (1)

brendosthoughts
brendosthoughts

Reputation: 1703

What about getting the resolution for the devices screen using something like this:

Display d = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screen_width = d.getWidth();
int screen_height = d.getHeight();

and then say if you want 4 buttons each with same width accross the screen calling from your example greenButton.setWidth(screen_width/4);

and do this for each of your buttons... same width spreading over a resolution of any size screen all dynamically done!

Upvotes: 1

Related Questions