如何以编程方式向RelativeLayout 添加视图?
问题描述:
你能给我一个非常简单的例子,在给定位置以编程方式将子视图添加到 RelativeLayout
吗?
Can you give me a very simple example of adding child view programmatically to RelativeLayout
at a given position?
例如,要反映以下 XML:
For example, to reflect the following XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="107dp"
android:layout_marginTop="103dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
我不明白如何创建一个合适的 RelativeLayout.LayoutParams
实例.
I don't understand how to create an appropriate RelativeLayout.LayoutParams
instance.
答
这是一个帮助您入门的示例,请根据需要填写其余部分:
Heres an example to get you started, fill in the rest as applicable:
TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);
RelativeLayout.LayoutParams 和构造函数的文档是 这里
The docs for RelativeLayout.LayoutParams and the constructors are here