title: Programmatically set button width to 50% of parent LinearLayout
body: <p>I created a Dialog using LinearLayout and in this Dialog, I have a Button. I want to set its width to 50% of the Dialog's width, but no matter what I do, the button is still filling the entire width. The main problem seems to be that I cannot set the button's weight programmatically. I tried creating a second horizontal LinearLayout that would hold the button with weight set to 0.5f (the parent has a weightSum of 1), but that did not change anything. How can I set the button to be half the width?</p>
  
  <p>I've looked at all the other questions but most of them were using xml so they were not relevant, and the one that solved it programmatically was using hardcoded values in pixels which is obviously an incorrect solution to the problem.</p>
  
  <p>EDIT: Adding some code</p>
  
  <pre><code>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);
  </code></pre>