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的边缘对齐。

相关内容

热门资讯

透视肯定"wejok... 1、透视肯定"wejoker辅助软件"详细辅助透牌教程(辅助是真的假的神器)(UU poker、we...
透视讲解"aapok... 透视讲解"aapoker辅助工具安全吗"详细辅助微扑克教程(有脚本神器);玩家必备必赢加哟《1367...
透视代打"wepok... 透视代打"wepoker游戏安装教程"详细辅助wpk教程(私人局透视技巧);大神普及一款德州ai内幕...
透视科技"wejok... 透视科技"wejoker黑侠辅助器"详细辅助技巧教程(祈福有用教程)这是由厦门游乐互动科技有限公司精...
透视教学"hhpok... 透视教学"hhpoker有后台操作吗"详细辅助系统教程(透视脚本免费app攻略)准备好在hhpoke...
透视安装"hhpok... 透视安装"hhpoker哪个俱乐部靠谱"详细辅助黑科技教程(私人局外卦教程);最新版2024是一款经...
透视神器"wepok... 自定义wepoker轻量版辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助...
透视教程"sohoo... 1、透视教程"sohoo开挂辅助"详细辅助介绍教程(破解辅助插件教程)。2、sohoo开挂辅助透视辅...
透视ai"sohoo... 1、透视ai"sohoo poker辅助"详细辅助必备教程(辅助脚本方法);详细教程。2、sohoo...
透视肯定"wepok... 1、透视肯定"wepoker有机器人吗"详细辅助扑克教程(私人局规律神器);详细教程。2、wepok...