我使用LinearLayout创建了一个Dialog,在这个Dialog中,我有一个Button。我想将其宽度设置为Dialog宽度的50%,但无论我做什么,按钮仍然会填满整个宽度。主要问题似乎是我无法以编程方式设置按钮的重量。我尝试创建第二个水平LinearLayout,它将按住权重设置为0.5f的按钮(父亲的weightSum为1),但这并没有改变任何东西。如何将按钮设置为宽度的一半?
我已经查看了所有其他问题,但大多数都使用xml,因此它们不相关,以编程方式解决它的是使用像素的硬编码值,这显然是解决问题的错误方法。
编辑:添加一些代码
LinearLayout linearLayout = new LinearLayout(mContext);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setWeightSum(1);
// I use these params when I call addContentView
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
testButton = new Button(mContext);
testButton.setText("Test");
testButton.setId(1);
testButton.setWidth(0);
testButton.setGravity(Gravity.CENTER);
LinearLayout buttonLayout = new LinearLayout(mContext);
butonLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
testButton.setLayoutParams(buttonParams);
buttonLayout.addView(testButton);
linearLayout.addView(buttonLayout);
...
this.addContentView(scrollView, layoutParams);
答案 0 :(得分:5)
当我尝试越来越多的选项时,代码变得一团糟。我决定从头开始,这段代码最终起作用了:
LinearLayout forButton = new LinearLayout(mContext);
forButton.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams forButtonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
forButton.setGravity(Gravity.CENTER);
DisplayMetrics dm = new DisplayMetrics();
this.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
forButton.addView(testButton);
testButton.getLayoutParams().width = width/2;
答案 1 :(得分:4)
您是否也将宽度值设置为0dp?这是布局引擎分别自动使用布局权重所必需的。
修改强>
我认为这一行会为您提供所需的结果:
LayoutParams buttonParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
答案 2 :(得分:3)
查找对话框宽度
DisplayMetrics dm = new DisplayMetrics();
dialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels ;
以编程方式设置值
final LayoutParams lparams = new LayoutParams(Height,width/2); // Width , height
final Button button = new Button(this);
button.setLayoutParams(lparams);
修改强>
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = 200;
lp.height = 200;
alertDialog.getWindow().setAttributes(lp);