0

I have tried to align 5 buttons in a LinearLayout with equal distance, everything looks good except the previous/next button, they have a bigger width. I am setting everything programmatically like this:

        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(width, height, 1f);
        buttonParams.gravity = Gravity.CENTER;

        next.setBackground(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.skipnext, null));
        previous.setBackground(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.skipprevious, null));
        shuffle.setButtonDrawable(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.shuffle, null));
        repeat.setButtonDrawable(android.support.v4.content.res.ResourcesCompat.getDrawable(getResources(), R.drawable.repeat, null));

        buttonsLayout.addView(repeat, buttonParams);
        buttonsLayout.addView(previous, buttonParams);
        buttonsLayout.addView(morphButton, buttonParams);
        buttonsLayout.addView(next, buttonParams);
        buttonsLayout.addView(shuffle, buttonParams);

        LinearLayout.LayoutParams buttonsParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        buttonsParams.gravity = Gravity.CENTER;
        buttonsParams.setMargins(0, marginTop, 0, marginBottom);
        addView(buttonsLayout, buttonsParams);
        buttonsLayout.setWeightSum(5);
        buttonsLayout.setGravity(Gravity.CENTER);

enter image description here

Marian Pavel
  • 2,726
  • 8
  • 29
  • 65

1 Answers1

2

Try assigning less weight to both buttons but the net sum should remain = 5. And there is no difference between xml code or java code in case of speed but according to android documentation:

The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages. Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems.

You can study more here: http://developer.android.com/guide/topics/ui/declaring-layout.html

and also take a look at this answer: Android xml vs java layouts performance

hope it helps.

Community
  • 1
  • 1
Umair
  • 6,366
  • 15
  • 42
  • 50