我如何在 android 中实用地添加和删除布局?

How can i add as well as remove layout pragmatically in android?

我想作为 AutoCompleteTextview 工作。但我没有在我的项目中使用自动完成文本视图。我使用了编辑文本并将它的值用于使用我正在创建动态按钮的适配器的那些值对适配器的值进行排序。但实际上,我想删除动态创建的按钮。当用户在这种情况下在编辑文本中输入新值时,它会根据必须创建的按钮对适配器中的新值进行排序。但是,我的问题是当用户在编辑文本视图中输入新文本时,动态创建的按钮不会被删除。它必须看起来像这样:

if (!s.equals("")) {
 final String query = s.toString().trim();
 filteredTags.clear();
 ((ViewManager) btnTag.getParent()).removeView(btnTag);


 for (int i = 0; i < TagArray.size(); i++) {

     final String tagName = TagArray.get(i).gettagName();

     if (tagName.contains(query)) {

         filteredTags.add(TagArray.get(i));

     }


 }

 count1 = filteredTags.size();

 layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
 layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"
 layout.setWeightSum(1);


 float rowneed = ((float) count1 / 5);
 k = 0;
 for (int i = 0; i < ceil(rowneed); i++) {
     row1 = new LinearLayout(getContext());
     row1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    /* layout.setVisibility(View.VISIBLE);
     row.setVisibility(View.VISIBLE);*/
     for (int j = 0; j < 5; j++) {

         btnTag = new Button(getContext());
         btnTag.setHeight(15);
         btnTag.setWidth(0);
         btnTag.setMinimumWidth(155);
         btnTag.setMinimumHeight(135);
         mTagList1 = new ArrayList<>();


         if (k < count1) {

             btnTag.setText(filteredTags.get(k).gettagName());
             btnTag.setId(k);

             k++;


             btnTag.setVisibility(View.VISIBLE);

         } else {
             btnTag.setVisibility(View.INVISIBLE);
         }
         Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
         btnTag.setTextSize(7);
         btnTag.setGravity(0);


         row1.addView(btnTag);


     }

     layout.addView(row1);


 }
 for (int btnId = 0; btnId < filteredTags.size(); btnId++) {

     btnTag = (Button) dialog.getCustomView().findViewById(btnId);
     final int finalId1 = btnId;

     btnTag.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
             TagNameArray.add(new Tags(filteredTags.get(finalId1).gettagId(), filteredTags.get(finalId1).gettagName()));
             // Log.e("button","Button clicked index = " + finalId +" "+ TagArray.get(finalId1).gettagName()+" "+TagNameArray.size());
         }
     });
 }

}

这可能对你有帮助,请给我一个反馈,希望我能帮助你

例如为 btnTag 设置一个动态标签

btnTag.setTag(DynamicTagInt++);

然后

row1.removeView(btnTag.findViewById(DynamicTagInt)); 
  //DynamicTagInt= the desired button that you want to delete

或者通过按钮的 ID 例如

row1.removeView(btnTag.findViewWithTag(k));

添加这行代码:
layout.removeAllViews(); layout.invalidate(); row.removeAllViews(); row.invalidate();