RelativeLayout.BELOW 无法运行

RelativeLayout.BELOW fails to function

基本上,我一直在尝试以编程方式放置一堆 EditText 和 TextViews,所有这些都在 RelativeLayout 中(我必须以编程方式进行,因为东西的数量是可变的,具体取决于 "employees"用户已输入)。现在,每个 "employee" 我只需要十条数据,所以我决定使用 id 以 10 为基数跟踪数据(即员工 1 获得 id 0-9,员工 2 获得 id 10-19,等等。 ).但是,每次我使用 LayoutParams.addRule(int,int) 函数并手动输入我自己的 id 时,它都无法拾取它。如果我使用 "R," 使用 addRule(int,int) 函数,它就可以工作。我能想到的唯一解释 addRule 无法响应手动输入的 id 值的原因是我的数学(对于 id 值)是错误的,但是如果你看看我的代码,数学是不言自明的.请告诉我我做错了什么,因为这太让人抓狂了。

这是我目前的情况:

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);
    }

*注:rl是我放在xml文件里的relativeLayout

我最近失去了发表评论的声誉 :) 所以我将其作为答案发布。您可以尝试使用线性布局而不是相对布局。如果您需要任何进一步的帮助,请告诉我。我会帮你的。 :)

错误是 ID 必须是正数。第一个 TextView 的 id 为 0,这解释了为什么 addRule 没有响应。