因此,我目前有一個android應用程序,只需按下一個按鈕即可添加和刪除一行線性佈局。線性佈局包含兩個edittext和兩個textview,但該行添加在列表的末尾,我想知道是否有方法添加/刪除取決於所選edittext的線性佈局的一行。如何在android studio中動態添加/刪除線性佈局
例如:我有4行線性佈局,第2行中的edittext被選中,我按下add按鈕,然後在第2行和第3行之間插入一行。 下面是我的代碼
ToggleButton timeTempToggle;
ArrayList<EditText> dataET = new ArrayList<>();
Button buttonAddStep,buttonRemoveStep;
int id=1; //the id number which indicates the number of commands that will be used
LinearLayout mainLayout; //orientation is vertical
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_parameters);
buttonAddStep = (Button) findViewById(R.id.buttonAddStep);
buttonRemoveStep = (Button) findViewById(R.id.buttonRemoveStep);
mainLayout = (LinearLayout) findViewById(R.id.mainlayout);
buttonAddStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(id<8) {
//adds a stage to be included (limit is 8)
id++;
mainLayout.addView(linearlayout(id,"","0"));
//append after all lines
}
}
});
buttonRemoveStep.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(id>1){ // removes a step from the list of steps
//removes the stage from the thermal cycling procedure
//will not remove the first step
id--;
mainLayout.removeViewAt(id);
dataET.remove(dataET.size()-1);
dataET.remove(dataET.size()-1);
//remove the last value and line
}
}
});
}
private LinearLayout linearlayout(int _intID, String et1, String et2)
{
LinearLayout LLMain=new LinearLayout(this);
LLMain.setId(_intID);
LLMain.addView(textView(_intID, String.valueOf(_intID) + " Temp (C): "));
LLMain.addView(editText(_intID, et1));
LLMain.addView(textView(_intID + 1, "Time(s): "));
LLMain.addView(editText(_intID + 1, et2));
LLMain.setOrientation(LinearLayout.HORIZONTAL);
return LLMain;
}
private EditText editText(int _intID,String preset) {
EditText editText = new EditText(this);
editText.setId(_intID);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setWidth(130);
editText.setText(preset);
dataET.add(editText);
return editText;
}
private TextView textView(int _intID,String Type)
{
TextView txtviewAll=new TextView(this);
txtviewAll.setId(_intID);
txtviewAll.setText(Type);
txtviewAll.setTypeface(Typeface.DEFAULT_BOLD);
return txtviewAll;
}