使用动态生成的editText添加删除选项

时间:2012-09-30 17:37:33

标签: android android-layout

我是android的新手,我在使用以下代码动态创建editText,同时点击添加新按钮。是否可以在editText附近添加删除按钮,以便每次单击删除相应的editText时都会被删除?

btnAddNew.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            LinearLayout rAlign = (LinearLayout)findViewById(R.id.lId);
            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(textb);

            rAlign.addView(newPass);
            MY_BUTTON ++;               
            addSpinner();               
        }
    });

1 个答案:

答案 0 :(得分:0)

是的,在EditText的同时创建删除按钮,并使用removeView()方法,就像addView()方法一样,可能是这样的:

btnAddNew.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        ...
        rAlign.addView(newPass);
        MY_BUTTON ++;               
        addSpinner();

        Button btnRemoveOld = new Button(this);
        btnRemoveOld.setId(32); // arbitrary number
        btnRemoveOld.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                LinearLayout rAlign = (LinearLayout)findViewById(R.id.lId);
                rAlign.removeView(findViewById(textb));
            }
        });     

        // You will need to set parameters to define how the button looks
        //   and where it is in relation to the EditText here
        rAlign.addView(btnRemoveOld);
    }
});