2017-01-09 102 views
0

因此,我目前有一个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; 
} 

回答

0

也许你可以构造一个ArrayList和第一修改。这样你可以管理列表中的事物序列。一旦你的ArrayList按你喜欢的顺序,将它添加到for-each循环到你想要的地方。

编辑。 1)这意味着你必须重新创建你的视图。 2)由于最大数量是8,它并不是很糟糕。如果数字是N,我不会推荐这个简单的解决方案。

0

使用void setVisibility (int visibility)使用的角度Visibility

here

enter image description here

相关问题