Home >Java >javaTutorial >How to set margins for buttons inside a LinearLayout programmatically?

How to set margins for buttons inside a LinearLayout programmatically?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 14:06:02892browse

How to set margins for buttons inside a LinearLayout programmatically?

Setting Margins in a LinearLayout Programmatically

To create a LinearLayout with evenly spaced buttons that occupy the entire screen, one must employ Java code instead of XML. However, achieving margins between buttons in this scenario has proven challenging for some developers.

One attempt involved utilizing LinearLayout.MarginLayoutParams, but it lacks a weight attribute and fails to work with the layout parameter object (lp). As a result, it appears that manipulating margins in this context may be impossible.

Solution:

Fortunately, it is possible to implement this functionality with a minor modification to the code:

<code class="java">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);</code>

In this code, the layout parameters for the button are created using LinearLayout.LayoutParams. The setMargins method is then used to specify the margins around the button, ensuring that it will be spaced from its neighboring buttons.

The above is the detailed content of How to set margins for buttons inside a LinearLayout programmatically?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn