AndroidStudioconstraintsetnotsettingconstraintsforprogrammaticallyaddedview
创始人
2024-10-11 05:30:13
0

在Android Studio中,有时无法使用ConstraintLayout的set方法来设置以编程方式添加的视图的约束条件。这通常是因为它们未被正确地添加到ConstraintLayout中。

解决这个问题的一种方法是在将视图添加到ConstraintLayout中之前,将其Constraints设置为null。然后再通过setConstraints方法将其添加到ConstraintLayout中。

以下是一个示例代码片段,展示如何编程设置ConstrainLayout中视图的约束条件:

// Create the ConstraintSet
ConstraintSet constraintSet = new ConstraintSet();

// Create the view programmatically
Button button = new Button(this);
button.setText("Programmatic Button");

// Add the view to the ConstraintLayout
ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraint_layout);
constraintLayout.addView(button);

// Set the constraints to null before adding them to the ConstraintSet
button.setId(View.generateViewId());
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,
                                ConstraintLayout.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(layoutParams);
button.setVisibility(View.VISIBLE);

// Apply the constraints to the view
constraintSet.clone(constraintLayout);
constraintSet.connect(button.getId(), ConstraintSet.LEFT, R.id.activity_main_layout, ConstraintSet.LEFT, 0);
constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.activity_main_layout, ConstraintSet.TOP, 0);
constraintSet.applyTo(constraintLayout);

这里的代码段将在ConstraintLayout中添加一个新的按钮,并将其左侧和顶部的边缘设置为与ConstraintLayout的边缘对齐。

相关内容

热门资讯

第9分钟讲义!人海大厅辅助插件... 第9分钟讲义!人海大厅辅助插件,拱趴大菠萝修改器,爆料教程(有挂教学)-哔哩哔哩人海大厅辅助插件辅助...
3分钟教程书!新众乐辅助,情怀... 3分钟教程书!新众乐辅助,情怀娱乐辅助器,德州论坛(有挂存在)-哔哩哔哩1、首先打开情怀娱乐辅助器最...
十分钟资料!白银胡乐白银版辅助... 十分钟资料!白银胡乐白银版辅助,小程序边锋辅助,普及教程(有挂工具)-哔哩哔哩1、白银胡乐白银版辅助...
第四分钟策略!途游手游辅助脚本... 第四分钟策略!途游手游辅助脚本平台,海盗来了辅助器最新,wpk教程(有挂实锤)-哔哩哔哩1、每一步都...
九分钟积累!传送屋激k有挂吗,... 九分钟积累!传送屋激k有挂吗,友友联盟辅助脚本,详细教程(竟然有挂)-哔哩哔哩1、游戏颠覆性的策略玩...
第十分钟诀窍!贪玩娱乐科技,闲... 第十分钟诀窍!贪玩娱乐科技,闲逸辅助脚本,解密教程(详细教程)-哔哩哔哩1、下载好贪玩娱乐科技辅助软...
第5分钟方案!新玄龙插件,开心... 第5分钟方案!新玄龙插件,开心泉州小程序辅助哪里查看,详细教程(有挂方法)-哔哩哔哩1、游戏颠覆性的...
第九分钟策略!老友麻将有没有挂... 第九分钟策略!老友麻将有没有挂,福建开心辅助,攻略教程(确实有挂)-哔哩哔哩1、进入游戏-大厅左侧-...
第五分钟诀窍!新漫游免费辅助器... 第五分钟诀窍!新漫游免费辅助器,老夫子拼十辅助,必赢方法(确实有挂)-哔哩哔哩1、上手简单,内置详细...
第八分钟演示!老友广东辅助工具... 第八分钟演示!老友广东辅助工具下载,中至抚州手麻工具,微扑克教程(有挂详细)-哔哩哔哩1、在老友广东...