Search code examples
androidandroid-relativelayout

RelativeLayout.BELOW fails to function


Basically, I've been trying to place a bunch of EditText and TextViews programmatically, all within a RelativeLayout (I have to do it programmatically because the amount of stuff is variable depending on how many "employees" the user has entered). Now, I only need ten pieces of data per "employee", so I decided to keep track of the data using id's in base 10 (ie Employee 1 gets id 0-9, Employee 2 gets id 10-19, etc.). However, every time I use LayoutParams.addRule(int,int) function and manually input my own id, it fails to pick it up. If I use the addRule(int,int) function using "R," it works. The only reason I can come up with that would explain addRule's failure to respond to the manually inputed id values is if my math (for the id-values) is wrong, but if you look at my code, the math is pretty self-explanatory. Please tell me what I'm doing wrong because this is maddening.

Here's what I have so far:

for(int i=0;i<u.getTemp().size();i++){
        int index=10*i;
        RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        if(i==0)
            layoutParams.addRule(RelativeLayout.BELOW,R.id.start_date);
        else
            layoutParams.addRule(RelativeLayout.BELOW,index-1);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

        TextView empName=new TextView(rl.getContext());
        empName.setTextSize(26);
        empName.setText(u.getTemp().get(i).getName());
        empName.setId(index++);
        empName.setLayoutParams(layoutParams);
        rl.addView(empName);

        TextView empNum=new TextView(rl.getContext());
        empNum.setText("Employee Number: " + u.getTemp().get(i).getNum());
        empNum.setId(index++);
        RelativeLayout.LayoutParams empNumLayout=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        empNumLayout.addRule(RelativeLayout.BELOW,empNum.getId()-1);
        empNumLayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        empNum.setLayoutParams(empNumLayout);
        rl.addView(empNum);

        EditText regHours=new EditText(rl.getContext());
        regHours.setHint("Regular Hours");
        regHours.setId(index++);
        RelativeLayout.LayoutParams regHoursLayout=new RelativeLayout.LayoutParams(300,RelativeLayout.LayoutParams.WRAP_CONTENT);
        regHoursLayout.addRule(RelativeLayout.BELOW,regHours.getId()-1);
        regHoursLayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        regHours.setLayoutParams(regHoursLayout);
        rl.addView(regHours);
    }

*Notes: rl is the relativeLayout I placed in the xml file.


Solution

  • The error was that ids have to be positive. The first TextView had an id of 0 which explains why the addRule didn't respond.