android - 如何从 Android 的布局中删除 Edittext?
问题描述
我能够在按钮单击时将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);
}
}
}
});
检查此图像以供参考:
解决方案
如果你想从布局中移除视图,你应该使用 removeView() 方法。在你的情况下:
mLayout.removeView(editText);
推荐阅读
- python - XHR 请求被阻止并使用 Python Selenium 显示 HTTP 状态代码 405
- mysql - 跨所有数据库的 mySQL 查询
- git - 通过 git 命令拉取和推送文件
- reactjs - 如果我将 useState 与部分更新回调一起使用,是否有充分的理由选择 useReducer 而不是 useState?
- sql - 比较分组结果与聚合结果
- javascript - 显示在线弹出聊天可用性状态
- c# - 无键实体类型 - EF Core 仍检查主键
- amazon-web-services - AWS FIFO Queues with lambda – 每个消息组一个并发 lambda
- php - PHP SQL 选择在哪里和
- mysql - 为什么mysql解释使用索引显示比int列更喜欢bigint列