我有一个arraylist,对于列表中的每个项目,输出项目旁边都有一个按钮,以便从列表中删除项目。Android - 查看动态创建,删除它们遗址布局
ArrayList<String> alString = new ArrayList();
//ArrayList gets filled with data items
RelativeLayout Container = (RelativeLayout) findViewById(R.id.container);
int Tracker = 500000000;
for (String item:alString){
final TextView textView = new TextView(this);
textView.setText(item);
textView.setId(Tracker);
//positioning
RelativeLayout.LayoutParams textViewParams = new
RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
textViewParams.addRule(RelativeLayout.BELOW,Tracker - 2);
textViewParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textView.setLayoutParams(textViewParams);
//Create button to remove ingredient
final Button Xbutton = new Button(this);
Xbutton.setText("X");
Xbutton.setId(Tracker + 1);
//positioning
RelativeLayout.LayoutParams XbuttonParams = new
RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
XbuttonParams.addRule(RelativeLayout.ALIGN_TOP,
textView.getId());
XbuttonParams.addRule(RelativeLayout.ALIGN_BOTTOM,
textView.getId());
XbuttonParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Xbutton.setLayoutParams(XbuttonParams);
//When button is clicked, remove the item
Xbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alString.remove(item);
Container.removeView(textView);
Container.removeView(Xbutton);
}
});
Container.addView(textView);
Container.addView(Xbutton);
Tracker = Tracker + 2;
}
}
的问题是,说有10个项目,我删除了第5和第7项与Xbuttons,很多项目的开始重叠。所有的观点最终都只是彼此重叠。如果我从上到下或从下到上逐个删除它们,则不会发生这种情况。但是,只要我删除列表中间的某个项目,它们都会开始互相重叠。我知道这是因为 跟踪器 - 2从textViewParams.addRule(RelativeLayout.BELOW,Tracker - 2)不再存在。但是,我需要这行代码,以便它们顺利进行。我该如何阻止TextViews重叠?