我试图将LinearLayout
中的5个按钮对齐距离相等,除了上一个/下一个按钮外,一切看起来都很好,它们的宽度更大。
我以编程方式设置所有内容:
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);
答案 0 :(得分:2)
尝试为两个按钮分配较少的权重,但净额应保持= 5。 在速度的情况下,xml代码或java代码之间没有区别,但是根据android文档:
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.
你可以在这里学习更多: http://developer.android.com/guide/topics/ui/declaring-layout.html
还要看一下这个答案: Android xml vs java layouts performance
希望它有所帮助。