问题描述
我有一个对话框,用户可以在其中添加 EditText 并删除它。 我已经成功地以编程方式添加了 EditText,但我的删除它的代码不起作用。 我正在关注教程,但在我的情况下,设置在对话框中。
而且我想获取这些 EditText 上的所有文本并将其存储在一个数组中。
这是我的代码:
public void showSurveyDialog(Context context) {
ImageButton btnAddChoices, btnRemoveChoice;
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.survey_content);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
btnAddChoices = dialog.findViewById(R.id.btn_add_choices);
LinearLayout choiceLayout = dialog.findViewById(R.id.choice_layout);
btnAddChoices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = dialog.getLayoutInflater().inflate(R.layout.choice_item, null);
// Add the new row before the add field button.
choiceLayout.addView(rowView, choiceLayout.getChildCount() - 1);
ImageButton imageButton = dialog.findViewById(R.id.btn_choice_close);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("asdass","ASDASd");
choiceLayout.removeView((View)v.getParent());
}
});
}
});
dialog.show();
}
当按 btnAddChoices 时,带有 EditText 和 Button(用于删除)的布局会自动添加到线性布局中。 我正在尝试使删除按钮工作,但它不会删除视图。
1楼
您可以尝试我添加和删除引用的代码,这可以以编程方式添加或删除视图:
private void addressField(View view){
final int[] textCount = {0};
LinearLayout addressLayout = view.findViewById(R.id.address_layout);
addressScroll.removeView(addressLayout);
View layout2 = LayoutInflater.from(view.getContext()).inflate(R.layout.address_text_field
, addressLayout,false);
layout2.setTag("address"+Integer.toString(counter));
addressLayout.addView(layout2);
addressScroll.addView(addressLayout);
ImageView deleteButton = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.delete_address);
TextFieldBoxes addressText = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.address_wrapper);
addressText.setSimpleTextChangeWatcher((theNewText, isError) -> {
if(Objects.equals(theNewText, "")){
textCount[0] = 0;
addressLayout.removeView(layout2);
}
if(theNewText.length() == 1 && textCount[0] == 0){
addressField(view);
ExtendedEditText addressText2 = layout2.findViewWithTag("address"+Integer.toString(counter-1))
.findViewById(R.id.address_text);
addressText2.requestFocus();
counter++;
}
textCount[0]++;
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addressLayout.removeView(layout2);
}
});
}
希望能解决你的问题