我使用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);
最佳答案
当我尝试越来越多的选项时,代码变得一团糟.我决定从头开始,这段代码最终起作用:
原文链接:https://www.f2er.com/android/430250.htmlLinearLayout 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;