Java 以编程方式将规则添加到已在布局中的视图-Android

Java 以编程方式将规则添加到已在布局中的视图-Android,java,android,android-layout,layoutparams,Java,Android,Android Layout,Layoutparams,如何向已在布局中的视图添加规则 我的XML: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relative_layout_id" android:layout_width="match_parent" android:layout_height="match_

如何向已在布局中的视图添加规则

我的XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relative_layout_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mylifeinformationsharedsocial.SexAcivity" >
<ListView
    android:id="@+id/list_view_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />    

</RelativeLayout>

它在
addView()
方法中抛出异常

,因此Matthias建议:

layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW,myView.getId());
listView.setLayoutParams(layoutParams);

无法添加视图,因为它已添加。因此,您需要设置正确的布局参数。您可以创建新的或检索当前的并修改它们。结帐


不要使用addView,而是使用setLayoutParams。“看!”马提亚斯·塞纳克说。我得到了它。
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW,myView.getId());
listView.setLayoutParams(layoutParams);
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW,myView.getId());
listView.setLayoutParams(layoutParams);