2012-05-02 64 views
51

你能给我一个非常简单的例子,在给定的位置以编程方式将子视图添加到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_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实例。

回答

91

这里有一个例子,让你开始,在填写其余如适用:

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

+0

对不起,同样的问题:你在哪里学习了没有Context作为第一个参数的'RelativeLayout.LayoutParams'构造函数? –

+1

@SuzanCioc请参阅上面的编辑 – JRaymond

+0

啊,对不起,认为宽度和高度应该是确切的值。 –

27

首先,你应该给一个id你RelativeLayout让我们说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); 
+0

“RelativeLayout.LayoutParams”构造函数的描述在哪里?这不是http://developer.android.com/reference/android/widget/RelativeLayout.html,因为所有的原型都有'Context'作为第一个参数。 –

+1

您应该检查这里http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html 这是RelativeLayout.LayoutParams(INT W,INT 1H) –

+0

什么是'R.id.relativeLayout1'指的是? – Si8

相关问题