Android 如何以编程方式将视图添加到 RelativeLayout?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10418929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a view programmatically to RelativeLayout?
提问by Suzan Cioc
Can you give me a very simple example of adding child view programmatically to RelativeLayout
at a given position?
你能给我一个非常简单的例子,以编程方式将子视图添加到RelativeLayout
给定位置吗?
For example, to reflect the following XML:
例如,要反映以下 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" />
I don't understand how to create an appropriate RelativeLayout.LayoutParams
instance.
我不明白如何创建一个合适的RelativeLayout.LayoutParams
实例。
回答by JRaymond
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);
The docs for RelativeLayout.LayoutParams and the constructors are here
RelativeLayout.LayoutParams 和构造函数的文档在这里
回答by Onuray ?ahin
Firstly, you should give an id to your RelativeLayout let say relativeLayout1.
首先,你应该给你的RelativeLayout 一个id,比如relativeLayout1。
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
TextView mTextView = new TextView(context);
mTextView.setText("Dynamic TextView");
mTextView.setId(111);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
mainLayout.addView(mTextView, params);