2

How do i add a rule to a View that is already in my layout?

My 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>

I want to add layoutParams.addRule(RelativeLayout.BELOW,myView.getId()); But if i add the View again to the layout it gives me an IllegalStateException(obviously Haha).

So how do i do that?

EDIT

Java:

listView = (ListView) findViewById(R.id.list_view_id);
listView.setAdapter(myArrayAdapter);

layoutParams.addRule(RelativeLayout.BELOW,datePicker.getId());
relativeLayout.addView(listView,layoutParams);

It throws the Exception at the addView() method

God
  • 1,238
  • 2
  • 18
  • 45
  • 4
    Don't use addView, but setLayoutParams. See [this post](http://stackoverflow.com/questions/10159372/android-view-layout-width-how-to-change-programmatically). – Matthias Jul 21 '15 at 15:29
  • @Matthias Thnaks man. i Got it. – God Jul 21 '15 at 15:41

2 Answers2

3

You can't add the view cause it's already added. So, you need to set the correct layout params. You can either create new ones or retrieve the current ones and alter those. Checkout this post.

layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW,myView.getId());
listView.setLayoutParams(layoutParams);
Community
  • 1
  • 1
Matthias
  • 5,574
  • 8
  • 61
  • 121
1

So as Matthias suggested:

layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW,myView.getId());
listView.setLayoutParams(layoutParams);
God
  • 1,238
  • 2
  • 18
  • 45