Programmatically set button width to 50% of parent LinearLayout
android, android-layout, android-linearlayout
Solution
As I tried more and more options, the code became a mess. I decided to start from scratch and this code worked in the end:
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;
Problem
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? 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. EDIT: Adding some 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); ```