我有以下代码来生成带有设置文本、onClick命令(或多或少)、高度、宽度和边距的按钮对象
private Button generateButton(String text, char command, int height, int width, int left, int top){
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(getDP(width),getDP(height));
lp.setMargins(getDP(left),getDP(top),0,0);
Button button = new Button(this.getContext());
button.setText(text);
button.setLayoutParams(lp);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Command",""+ command);
}
private char command;
private View.OnClickListener init(char var){
command = var;
return this;
}
}.init(command));
return button;
}与此方法一起来获得dp
private int getDP(int size){
return (int) (size * this.getContext().getResources().getDisplayMetrics().density);
}但当我运行应用程序时,按钮有适当的高度和宽度,以及适当的文本和onclick操作,但它们没有页边距,它们都集中在一个角落里
根据Android studio中的布局检查器,视图层次结构如下
DecorView
LinearLayout
FrameLayout
FitWindowLinearLayout
ContentFrameLayout
CoordinatorLayout
ViewPager
ConstraintLayout
ConstraintLayout
Buttons根据我在网上读到的内容,LayoutParams必须与布局来自同一个类,就像LinearLayout.LayourParams或ConstraintLayout.LayoutParams一样,我尝试了所有对我有意义的布局类型,但仍然没有页边距
值得注意的是,这是一个片段
发布于 2019-11-19 14:59:12
对于ConstraintLayout的子视图,您需要添加水平和垂直约束。否则,它们的布局将不知道如何放置它们,并将它们放置在左上角。
可以使用ConstraintLayout.LayoutParams,并通过以下方式设置约束
lp.leftToLeft、lp.leftToRight和类似的方法here
因此,例如,如果您想要一个接一个地垂直放置这些按钮,则需要将每个按钮水平约束到父按钮,并垂直约束到上一个按钮。
发布于 2019-11-19 14:48:36
public void setMargins (int left, int top, int right, int bottom)这是setMargins方法的签名。您使用right = 0和bottom =0调用该方法。所以你不会有右边和底部的页边距。尝试为right和bottom设置一些值。
发布于 2019-11-19 15:24:13
你应该使用LayoutParams来设置你的按钮边距:`
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);根据您使用的布局,您应该使用RelativeLayout.LayoutParams或LinearLayout.LayoutParams。
要将dp度量转换为像素,请尝试执行以下操作:
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);`
https://stackoverflow.com/questions/58927917
复制相似问题