如何添加以及在Android中实际删除布局?

时间:2017-01-07 12:41:38

标签: android android-layout android-adapter android-button

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

enter image description here

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());
         }
     });
 }

}

2 个答案:

答案 0 :(得分:2)

添加以下代码:
layout.removeAllViews(); layout.invalidate(); row.removeAllViews(); row.invalidate();

答案 1 :(得分:0)

这可能会对您有所帮助,请给我一些反馈,希望我能为您提供帮助

为btnTag设置动态标记,例如

btnTag.setTag(DynamicTagInt++);

然后

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

或按钮的ID,例如

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