问题描述
我尝试以编程方式添加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);
解决方法
您正在向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
)