Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何以编程方式将视图添加到RelativeLayout?_Android_Android Layout_Android Relativelayout - Fatal编程技术网

Android 如何以编程方式将视图添加到RelativeLayout?

Android 如何以编程方式将视图添加到RelativeLayout?,android,android-layout,android-relativelayout,Android,Android Layout,Android Relativelayout,你能给我一个非常简单的例子,以编程方式将子视图添加到给定位置的RelativeLayout 例如,要反映以下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_paren

你能给我一个非常简单的例子,以编程方式将子视图添加到给定位置的
RelativeLayout

例如,要反映以下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
实例。

下面是一个示例,让您开始学习,如果适用,请填写其余部分:

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的文档和构造函数是

首先,您应该为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);

哪里描述了
RelativeLayout.LayoutParams
构造函数?它不在这里,因为所有原型都将
上下文作为第一个参数。您应该在这里检查它是RelativeLayout.LayoutParams(int w,int h)什么是
R.id.relativeLayout1
指的是?@SiKni8它是TextView父布局的id,一个已经在xml文件中的相对布局。对不起,同样的问题:您从哪里了解到没有上下文作为第一个参数的
RelativeLayout.LayoutParams
构造函数?啊,很抱歉,我认为宽度和高度应该是精确的值。我正在寻找这个!即使我的观点似乎不适用于参数。。。