【问题标题】:how to remove dynamically inflated views?如何删除动态膨胀的视图?
【发布时间】:2012-07-03 20:46:12
【问题描述】:

在我想开发的一个简单的纸牌游戏中,我有三个按钮:button1、button2 和 button3。 button1 在一个表格行中创建两个图像视图并显示图像。当 button2 和/或 button3 被点击时,它会通过布局充气器在 tablerow 上动态添加 imageview。游戏结束后,我希望用户单击 button1 并重新开始。我能够做到这一点,但问题是,以前通过单击 button2 和 button3 显示的图像视图也会显示。我希望在单击 button1 时将它们删除。如何在单击 button1 时删除它们? 请帮帮我!

【问题讨论】:

    标签: android


    【解决方案1】:

    就像您添加视图一样,您可以删除它们。只需在父容器上调用 removeViewAt(int index)removeView(View view) 即可删除所需的视图。

    或者,如果您预见到重复使用它们,您可以将它们的可见性设置为GONE。然后,您可以将它们带回来,而无需再次膨胀它们。

    如果您让充气器自动将充气后的图像视图附加到父级,那么您必须跟踪添加的视图的位置。您可以在膨胀之前在父级上使用 getChildCount 以查找将要添加的下一个视图的索引。

    【讨论】:

      【解决方案2】:

      你可以使用ViewGroup.removeView(View v);

      类似这样的:

      tblRow.removeView(button2);
      

      【讨论】:

      • 我这样做了,但是当我单击 button1 时它没有添加图像视图。我只想删除布局充气器显示的图像视图。而且我不想删除按钮!我想删除 imageViews。
      • 然后将 removeView() 传递给要删除的 ImageView 的引用,而不是按钮。如果您编辑您的问题并发布一些您正在使用的代码,我们会更容易为您提供具体的解决方案。由于现在很难根据您发布的内容准确判断程序中发生了什么。
      【解决方案3】:

      这是我如何添加然后在 5 秒后删除视图(在另一个上下文中)

        final LinearLayout linearLayout = context.getResources().getLayout(R.layout.activity_main)
        LayoutInflater inflater = LayoutInflater.from(linearLayout.getContext());
        final View details = inflater.inflate(R.layout.extra_details, linearLayout, false);
        linearLayout.addView(details);
      
        new Handler().postDelayed(new Runnable() {
                      @Override
                      public void run() {
                          if (linearLayout.findViewById(R.id.extra_details) != null){
                              linearLayout.removeView(details);
                          }
                      }
                  }, 5000);
      

      同样的使用场景是在onClickListener的上下文中。 在这里查看更多https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

      【讨论】:

        【解决方案4】:

        //添加视图

        LayoutInflater inflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        final View buttons = inflater.inflate(R.layout.activity, null );
        addContentView(buttons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        

        //删除视图

        ((ViewManager)buttons.getParent()).removeView(buttons);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-04-28
          • 2011-08-29
          • 1970-01-01
          • 2016-08-03
          • 1970-01-01
          • 1970-01-01
          • 2015-03-15
          相关资源
          最近更新 更多