2015-07-21 1 views
1

Comment ajouter une règle à une vue déjà présente dans ma mise en page?Ajout de règle par programmation à une vue déjà présente dans la mise en page - Android

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

Je veux ajouter layoutParams.addRule(RelativeLayout.BELOW,myView.getId()); Mais si j'ajouter la vue à nouveau à la mise en page, il me donne un IllegalStateException (évidemment Haha).

Alors, comment je fais ça?

EDIT

Java:

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

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

Il lève l'exception à la méthode addView()

+4

N'utilisez pas addView, mais setLayoutParams. Voir [ce post] (http://stackoverflow.com/questions/10159372/android-view-layout-width-how-to-change-programmatically). – Matthias

+0

@Matthias L'homme de Thnaks. je l'ai. – God

Répondre

2

Vous ne pouvez pas ajouter la vue parce que c'est déjà ajouté. Donc, vous devez définir les paramètres de mise en page corrects. Vous pouvez soit en créer de nouveaux ou récupérer les actuels et les modifier. Commander this post.

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

Alors que Matthias a suggéré:

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