Android 动态创建RelativeLayout,设置宽高和边距
时间: 2024-06-13 10:08:02 浏览: 184
android RelativeLayout
以下是Android动态创建RelativeLayout,设置宽高和边距的示例代码:
```java
// 创建RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// 设置RelativeLayout的宽高和边距
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, // 宽度为MATCH_PARENT
RelativeLayout.LayoutParams.WRAP_CONTENT // 高度为WRAP_CONTENT
);
layoutParams.setMargins(10, 20, 30, 40); // 设置边距
relativeLayout.setLayoutParams(layoutParams);
// 将RelativeLayout添加到父布局中
ViewGroup parentLayout = findViewById(R.id.parent_layout);
parentLayout.addView(relativeLayout);
```
上述代码中,首先创建了一个RelativeLayout对象,然后通过RelativeLayout.LayoutParams设置了宽高和边距,最后将RelativeLayout添加到父布局中。
阅读全文