【问题标题】:How to add imageviews to constraint layout如何将图像视图添加到约束布局
【发布时间】:2019-05-04 23:19:49
【问题描述】:

我有一个约束布局。我以编程方式将具有随机图片的图像视图添加到约束布局。当用户单击“新游戏”按钮时,我想删除以编程方式创建的所有图像视图并随机重新创建它们。

当我编写下面的代码时,我的图像正在创建,但旧图像仍然存在。如何在没有旧图像视图的情况下重新加载约束布局?

CLCarrier.addView(Cards[i], -1);

【问题讨论】:

    标签: android layout imageview android-constraintlayout


    【解决方案1】:

    这里有几种不同的方法可以做到这一点。

    从您的 ConstraintLayout 中删除所有视图

    所有ViewGroup 子类都支持removeAllViews() 方法。这将删除当前在 ViewGroup 中的每个子项,因此仅当您想摆脱 everything 时才合适。如果您想保留一些视图,这将不起作用。

    在添加时跟踪 ImageView,然后逐个删除它们

    也许您在某处保留了一个List<ImageView> images 变量,并且当您将图像添加到您的ConstraintLayout 时,您还调用了images.add(myImageView)。然后,这将为您提供一组视图,您可以对其进行迭代并调用removeView()

    for (ImageView image : images) {
        constraintLayout.removeView(image);
    }
    

    重新膨胀原来的 ConstraintLayout

    如果您不想使用removeAllViews() 并且您也不想跟踪所有视图以便以后删除它们,您可以通过重新膨胀原始布局来重新初始化您的 ConstraintLayout。

    LayoutInflater inflater = LayoutInflater.from(this); // requires a `Context` object
    constraintLayout = inflater.inflate(R.layout.constraint_layout, parent, false);
    

    【讨论】:

    • 谢谢 Ben,你的回答非常有解释性。
    猜你喜欢
    • 2019-02-20
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多