【发布时间】:2021-02-10 19:18:29
【问题描述】:
我能够在按钮单击时将edittext 动态添加到布局中。 现在我希望用户也能够删除相应的编辑文本。
我可以从 arraylist 中删除 edittext,但我也希望它从我的布局/屏幕中消失。
我该怎么做? 可能吗? 任何帮助,将不胜感激。 提前谢谢你。
代码参考:
首先将Edittext添加到arraylist:
ArrayList<EditText> list = new ArrayList<>();
ArrayList<Button> listbtn = new ArrayList<>();
第 2 步:
spinnerAdd_Field.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener()
{
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, final Object item)
{
// Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
{
editText = new EditText(Add_Account.this);
btnremove = new Button(Add_Account.this);
RelativeLayout.LayoutParams lpb = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 120);
lpb.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
lpb.setMargins(0, 0, 0, 32);
btnremove.setLayoutParams(lpb);
btnremove.setPadding(46, 0,0,0);
btnremove.setText( "Remove\n"+item.toString());
btnremove.setId(count);
btnremove.setTextColor(Color.parseColor("#000000"));
btnremove.setBackgroundResource(R.drawable.backgroundrounded);
btnremove.setOnClickListener(btnclick);
{
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 120);
lp.setMargins(0, 0, 0, 32);
editText.setLayoutParams(lp);
editText.setPadding(46, 0,0,0);
editText.setHintTextColor(Color.parseColor("#A17A7979"));
editText.setBackgroundResource(R.drawable.rounded_edittex);
editText.setTextColor(Color.parseColor("#7A7979"));
editText.setHint(item.toString());
}
if(btnremove.getParent() != null) {
((ViewGroup)btnremove.getParent()).removeView(btnremove); // <- fix
}
myLayout.addView(editText);
myLayoutbtn.addView(btnremove);
// for each EditText add it to the ArrayList
for(int i=0; i < count; i++)
{
list.add(editText);
}
// for each Button also add it to the ArrayList
for(int i=0; i < count; i++)
{
listbtn.add(btnremove);
}
}
}
});
查看此图片以供参考:
【问题讨论】:
-
您可以将可见性设置为INVISIBLE。
标签: android android-layout android-edittext