我想在我的应用程序中实现的是动态创建一组具有不同文本大小的按钮,然后在线性布局中对齐这些视图。以下是我想要实现的目标示例:
。根据文本大小,我希望按钮在一行中对齐,如果最后一个按钮大于屏幕尺寸,它应该正确地转到下一行。
任何建议如何实现这一点或我应该寻找什么,因为我知道如果我尝试button.getWidth();
它将返回0并且它将无效。
感谢您提出任何建议!
修改
答案 0 :(得分:2)
感谢@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.
}
答案 1 :(得分:1)
您可以尝试以下操作 添加按钮时,您可以计算直到占用的宽度
occupiedWidth = button1Width + button2Width + ...
每个按钮宽度= textWidth + 2 * margin + 2 * padding
您可以获得放在按钮上的文字宽度,如
String buttonText = "<Your Button Text>"
paint.getTextBounds(buttonText, 0, buttonText.length(), bounds);
int textWidth = bounds.width();
将此新按钮边距和填充添加为
int newWidth = textWidth + buttonMargin*2 + buttonPadding*2;
如果总宽度超过屏幕宽度,则移至下一行。
答案 2 :(得分:0)
据我所知,您有两种选择:
1)以linear layout
方向取horizontal
。
并以编程方式继续向此布局添加按钮。
如果按钮的宽度不适合该行,它将自动转到线性布局的下一行。
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
2)你可以计算@kameswari所提到的每个按钮的x,y位置,并在x,y位置绘制相应的按钮
Button button = (Button)findViewById(R.id.button);// or new Button(this);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)button.getLayoutParams();
absParams.x = X;
absParams.y = Y;
button.setLayoutParams(absParams);
答案 3 :(得分:0)
u can try this `enter code here`
LinearLayout.LayoutParams leftMarginParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftMarginParams.leftMargin = 50;
Button btn1 = new Button(this);
btn1.setText("Button1");
linLayout.addView(btn1, leftMarginParams)