Android ConstraintLayout ConstraintLayout.LayoutParams.WRAP_CONTENT无法正常工作

问题描述

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

“ Android开发者”页面未列出ConstraintLayout.LayoutParamsWRAP_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);

解决方法

您正在向ConstrainLayout添加视图(RelativeLayout),因此应使用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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...