This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

preface

Try using Java (not XML) to create a linear layout that fills the screen with buttons and has margins; To create a linear layout and fill screen with buttons in Java (not XML), there are a few questions that need to be resolved.

Problem of repetition

The problem now we can reproduce the problem in code.

The code is as follows:

LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
for (int r = 0; r < 6; ++r) {
    Button btn = new Button(this);
    btn.setText("A");

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
    lp.weight = 1.0 f; // This is critical. Doesn't work without it.
    buttonsView.addView(btn, lp);
}

ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
setContentView(buttonsView, lp);
Copy the code

The code is fine, but how does the border add space between the button edges?

Try using LinearLayout. MarginLayoutParams implemented, but still can not achieve, because there is no weight parameters

Just like that, in trouble.

Problem solving

In fact, we can solve this problem by doing so

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(30.20.30.0);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
Copy the code

conclusion

When developing Android apps, there are all sorts of issues that need to be addressed with a little care.