AJ72 AJ72 - 6 months ago 33
Android Question

How does LayoutParams.addRule work?

I am building an application that will add views to a relative layout until stopped.
My question is how does RelativeLayout.LayoutParams.addRule work? If I keep calling addRule will this create an ever growing list or does addRule check if a rule already exists? Is the following code really neccessary? Can I just use addRule and if already exists this will not create a duplicate entry?

Thanks

int[] rules = this.position[0].params.getRules();
boolean rule = false;

switch(index){
case 0:

for(int i = 0; i < rules.length; i++){
if(rules[i]==RelativeLayout.RIGHT_OF)
rule = true;
}

if(!rule){
this.position[0].params.addRule(RelativeLayout.RIGHT_OF);
}

break;
case 1:

for(int i = 0; i < rules.length; i++){
if(rules[i]==RelativeLayout.LEFT_OF)
rule = true;
}

if(!rule){
this.position[1].params.addRule(RelativeLayout.LEFT_OF);
}

break;
case 2:

for(int i = 0; i < rules.length; i++){
if(rules[i]==RelativeLayout.ABOVE)
rule = true;
}

if(!rule){
this.position[2].params.addRule(RelativeLayout.ABOVE);
}

break;
case 3:

for(int i = 0; i < rules.length; i++){
if(rules[i]==RelativeLayout.BELOW)
rule = true;
}

if(!rule){
this.position[3].params.addRule(RelativeLayout.BELOW);
}

break;
}

Answer

By looking at the code for the RelativeLayout.LayoutParams class you can see that the rules are stored in an int array where the rules are the indexes, so the rules will be added only once no matter how many times you call addRule(the last call will count).