Search code examples
javaandroidandroid-buttonandroid-gridlayoutandroid-togglebutton

Buttons and ToggleButtons not lining up


I am adding a button and toggle button side by side into a gridlayout programmatically. My problem is these buttons aren't lining up.

Relevant code :

tempBtn = new Button(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        scrnWidth/2, LayoutParams.WRAP_CONTENT);
params.weight = 0.5f;
tempBtn.setLayoutParams(params);
tempBtn.setGravity(Gravity.LEFT);

Same code for a toggle button. The gridlayout is inside a relativelayout. I have tried all kinds of variations of layout params aswell as trying different ways of using weigths, none of it has worked. If I don't set the width the buttons are more closely lined up, but still not 100% and I do need these to be half the screen each.


Solution

  • I have found the solution in this question : Android Button in Gridlayout don't have same margin top

    Just changed

    tempBtn.setGravity(Gravity.LEFT);
    

    to

    tempBtn.setGravity(Gravity.FILL_VERTICAL);