gpt4 book ai didi

Android ConstraintLayout ConstraintLayout.LayoutParams.WRAP_CONTENT 不工作

转载 作者:行者123 更新时间:2023-12-05 00:04:27 34 4
gpt4 key购买 nike

我尝试以编程方式添加 ConstraintLayout。它在工作,但 WRAP_CONTENT 不工作。布局始终为 MATCH_PARENT

Android 开发者页面没有为 ConstraintLayout.LayoutParams 列出 WRAP_CONTENT

我的代码:

RelativeLayout rl_main = findViewById(R.id.rl_main);
ConstraintLayout cl = new ConstraintLayout(this);
cl.setId(0);
ConstraintLayout.LayoutParams clp = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_WRAP);
cl.setLayoutParams(clp);
cl.setBackgroundColor(Color.parseColor("#000000"));
rl_main.addView(cl);

最佳答案

您正在向 RelativeLayout 添加 View (ConstrainLayout),因此您应该使用 RelativeLayout 参数。试试这个(同时检查您的导入是否正确):

import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RelativeLayout rl_main = findViewById(R.id.rl_main);
ConstraintLayout cl = new ConstraintLayout(this);
cl.setId(0);
RelativeLayout.LayoutParams clp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

cl.setLayoutParams(clp);
cl.setBackgroundColor(Color.parseColor("#FF0000"));
rl_main.addView(cl);

//test adding button
cl.addView(new Button(this));
}
}

结果(红色背景的约束布局为WRAP_CONTENT):

enter image description here

关于Android ConstraintLayout ConstraintLayout.LayoutParams.WRAP_CONTENT 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63345836/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com