草庐IT

android - 将动态 subview 垂直添加到 ConstraintLayout

coder 2023-12-20 原文

Android ViewGroup 具有以下添加(子) View 的方法:

我知道我们可以轻松地在 xml 中/以编程方式为 LinearLayout 定义水平/垂直方向,并添加 subview ,例如。

与RelativeLayout类似,我们可以使用ViewGroupaddViewRelativeLayout.LayoutParams的方法:

我还知道我们可以在 ConstraintLayout 中使用 LinearLayout 作为子项并使用它。

是否有任何可靠的推荐方法可以动态地将 subview 添加到 ConstraintLayout?

更新: 让我举一个我想要实现的不太简单的例子。

假设您有一个View1、View2 和View3。所有 V1、V2 和 V3 都在垂直方向上依次排列,并且是由多个 TextViewImageView 组成的复杂 View 。根据用户操作和服务器发送的信息,我需要在原始 V2 和 V3 之间添加多个 V1 和 V2(可以是 1 对 V1-V2,也可以是 3 对 V1-V2)。如果我正在使用 ConstraintLayout,当我可以轻松地使用垂直方向的 LinearLayout 时,最好以编程方式添加多个约束吗?

现在,就效率、性能和简洁美观的代码而言,与线性布局相比,ConstraintLayout 是否最适合此要求?

最佳答案

可以像使用 LinearLayout 一样使用 addView() 将 View 添加到 ConstraintLayout。不同之处在于,使用 ConstraintLayout 时,必须限制添加的 View 。要以编程方式约束 View ,请使用 ConstraintSet .

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout.

这是一个简单的例子:

activity_main
定义两个 TextViews。它们水平居中并位于顶部。

<android.support.constraint.ConstraintLayout 
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/topView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Top View"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/bottomView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Bottom View"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/topView" />

</android.support.constraint.ConstraintLayout>

这是在未设置约束的情况下将新的 TextView(“中间 View ”)添加到此布局时您将看到的内容。请注意,新 View 默认位于位置 (0,0)。

假设我们希望生成的中间 View 像这样在窗口中水平居中放置在顶 View 和底 View 之间:

这是将产生此结果的代码:

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Define the new TextView and add it to the ConstraintLayout. Without constraints,
    // this view will be positioned at (0,0).
    TextView middleView = new TextView(this);
    middleView.setId(View.generateViewId());
    middleView.setText("Middle View");
    middleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20.0f);
    ConstraintLayout layout = findViewById(R.id.constraintLayout);
    ConstraintLayout.LayoutParams lp =
        new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,
                                          ConstraintLayout.LayoutParams.WRAP_CONTENT);
    layout.addView(middleView, lp);

    // Move the new view into place by applying constraints.
    ConstraintSet set = new ConstraintSet();
    // Get existing constraints. This will be the base for modification.
    set.clone(layout);
    int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                                                    16, getResources().getDisplayMetrics());
    // Set up the connections for the new view. Constrain its top to the bottom of the top view.
    set.connect(middleView.getId(), ConstraintSet.TOP, R.id.topView, ConstraintSet.BOTTOM, topMargin);
    // Constrain the top of the bottom view to the bottom of the new view. This will replace
    // the constraint from the bottom view to the bottom of the top view.
    set.connect(R.id.bottomView, ConstraintSet.TOP, middleView.getId(), ConstraintSet.BOTTOM, topMargin);
    // Since views must be constrained vertically and horizontally, establish the horizontal
    // constaints such that the new view is centered.
    set.centerHorizontally(middleView.getId(),ConstraintSet.PARENT_ID);
    // Finally, apply our good work to the layout.
    set.applyTo(layout);
}

关于android - 将动态 subview 垂直添加到 ConstraintLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52492674/

有关android - 将动态 subview 垂直添加到 ConstraintLayout的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  5. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  6. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  7. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  8. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  9. ruby-on-rails - 在 Ruby on Rails 中添加 boolean 列值 - 2

    我正在开发一个创建网络博客的RubyonRails项目。我希望将一个名为featured的boolean数据库字段添加到Post模型中。该字段应该可以通过我添加的事件管理界面进行编辑。我使用了以下代码,但我什至没有在网站上显示另一列。$railsgeneratemigrationaddFeaturedfeatured:boolean$rakedb:migrate我是RubyonRails的新手,非常感谢任何帮助。我的index.html.erb文件中的相关代码(views):FeaturedPost架构.rb:ActiveRecord::Schema.define(:version=>

  10. ruby - 如何将便捷类方法添加到 ruby​​ 中的 Singleton 类 - 2

    假设我有一个这样的单例类:classSettingsincludeSingletondeftimeout#lazy-loadtimeoutfromconfigfile,orwhateverendend现在,如果我想知道使用什么超时,我需要编写如下内容:Settings.instance.timeout但我宁愿将其缩短为Settings.timeout使这项工作有效的一个明显方法是将设置的实现修改为:classSettingsincludeSingletondefself.timeoutinstance.timeoutenddeftimeout#lazy-loadtimeoutfromc

随机推荐