视图不会删除

时间:2012-10-01 14:28:43

标签: android android-layout

我已经问过问题(http://stackoverflow.com/questions/12663443/add-delete-option-with-dynamically-generated-edittext)。我成功地实现了答案,但是这个代码的问题是textEdit,spinner和remove按钮一起不会从视图中删除。它发生但我必须点击三个按钮发生这个..请仔细检查我的代码。

 btnAddNew.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            LinearLayout rAlign = (LinearLayout)findViewById(R.id.lId);
            final EditText newPass = new EditText(getApplicationContext());
            allEds.add(newPass);
            newPass.setHint("Name of Label");
            newPass.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            //newPass.setWidth(318);
            newPass.setTextColor(Color.parseColor("#333333"));
            newPass.setId(MY_BUTTON);
             System.out.println(MY_BUTTON);  
            //newPass.setOnClickListener(this);
            rAlign.addView(newPass);

            addSpinner();//Code to add spinner              
            Button btnRemoveOld = new Button(getApplicationContext());
            btnRemoveOld.setId(MY_BUTTON); // arbitrary number
            rAlign.addView(btnRemoveOld);
            btnRemoveOld.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    int idf =MY_BUTTON -1;
                    LinearLayout rAlign = (LinearLayout)findViewById(R.id.lId);
                    rAlign.removeView(findViewById(idf));
                  allEds.remove(newPass);

                }
            }); 
           MY_BUTTON ++;
        } 
    });

1 个答案:

答案 0 :(得分:0)

如果您使用MY_BUTTON为每个视图分配ID

newPass.setId(MY_BUTTON); 
MY_BUTTON++;
spinner.setId(MY_BUTTON);
MY_BUTTON++;
btnRemoveOld.setId(MY_BUTTON);
MY_BUTTON++;

你可以在btnRemoveOld的onClickListner中删除所有三个对象

btnRemoveOld.setOnClickListener(new OnClickListener() {
              public void onClick(View v) {
                  //gets the ID of the btnRemoveOld;
                  int idf =v.getId();
                  LinearLayout rAlign = (LinearLayout)findViewById(R.id.lId);
                  //will return the newPass button
                  rAlign.removeView(findViewById(idf-2));
                  //will return the spinner
                  rAlign.removeView(findViewById(idf-1));
                  //will remove the btnRemoveOld
                  rAlign.removeView(v);
                    }
          });

通过执行v.getId(),您将获得btnRemoveOld的id值,并从代码中确保微调器是id-1,newPass按钮是id-2。 / p>

相关问题