我想在我的应用程序中实现的是动态创建一组具有不同文本大小的按钮,然后将这些 View 对齐到线性布局中。这是我想要实现的示例:
.根据文本大小,我希望按钮在一行中对齐,如果最后一个按钮大于屏幕大小,它应该正确地转到下一行。
任何关于我如何实现这个或我应该寻找什么的建议,因为我知道如果我尝试 button.getWidth();
它会返回 0 并且它不会工作。
感谢您的任何建议!
编辑
要实现此目的,您可以使用 Google 开源的新布局,称为:FlexboxLayout .您可以在此 post 中了解更多信息来自 Android 开发者博客。
最佳答案
感谢@Kameswari 的代码,它给了我正确的方向,我通过使用实现了这一点:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
String[] mKeywordsArray = mKeywords.split(", ");
if(mKeywordsArray != null){
LinearLayout mNewLayout = new LinearLayout(getActivity()); // Horizontal layout which I am using to add my buttons.
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
int mButtonsSize = 0;
Rect bounds = new Rect();
for(int i = 0; i < mKeywordsArray.length; i++){
String mButtonTitle = mKeywordsArray[i];
Button mBtn = new Button(getActivity());
mBtn.setPadding(10, 3, 10, 3);
mBtn.setText(mButtonTitle);
Paint textPaint = mBtn.getPaint();
textPaint.getTextBounds(mButtonTitle, 0, mButtonTitle.length(), bounds);
// size of all buttons in current horizontal layout
// i am using +45 because of extra padding which is set in xml for this layout
mButtonsSize += ( bounds.width() + 45);
if(mButtonsSize < (mScreenWidth - 32)){ // -32 because of extra padding in main layout.
mNewLayout.addView(mBtn, params);
} else {
mButtonsLayout.addView(mNewLayout);
mNewLayout = new LinearLayout(getActivity());
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
mButtonsSize = bounds.width();
mNewLayout.addView(mBtn, params); // add button to a new layout so it won't be stretched because of it's width.
}
}
mButtonsLayout.addView(mNewLayout); // add the last layout/ button.
}
关于Android 在布局中以编程方式对齐一组按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15967074/