我正在尝试将图像视图与约束布局的中心对齐。我正在编写下面的代码,但它不起作用。
代码
int size = 150;
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(size, size);
layoutParams.bottomToBottom = ConstraintSet.PARENT_ID;
layoutParams.endToEnd = ConstraintSet.PARENT_ID;
layoutParams.startToStart = ConstraintSet.PARENT_ID;
layoutParams.topToTop = ConstraintSet.PARENT_ID;
circleImageView.setLayoutParams(layoutParams);
答案 0 :(得分:0)
尝试使用 ConstraintSet ,您可以轻松地以 ConstraintLayout 的形式将视图以编程方式呈现到中心。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setId(R.id.imageview);
ConstraintLayout myLayout = new ConstraintLayout(this);
myLayout.setBackgroundColor(Color.BLUE);
myLayout.addView(imageView);
setContentView(myLayout);
ConstraintSet set = new ConstraintSet();
set.constrainHeight(imageView.getId(),
ConstraintSet.WRAP_CONTENT);
set.constrainWidth(imageView.getId(),
ConstraintSet.WRAP_CONTENT);
set.connect(imageView.getId(), ConstraintSet.LEFT,
ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 0);
set.connect(imageView.getId(), ConstraintSet.RIGHT,
ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.connect(imageView.getId(), ConstraintSet.TOP,
ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
set.connect(imageView.getId(), ConstraintSet.BOTTOM,
ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
set.applyTo(myLayout);
}
答案 1 :(得分:0)
在您的代码中:
ConstraintSet.PARENT_ID
不是父约束布局的真实ID。您需要将其更改为:
R.id.myLayout
您在* .xml文件中键入的myLayout:
android:id="@+id/myLayout"
这应该有效:
int size = 150;
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(size, size);
layoutParams.topToTop = R.id.myLayout;
layoutParams.bottomToBottom = R.id.myLayout;
layoutParams.leftToLeft = R.id.myLayout;
layoutParams.rightToRight = R.id.myLayout;
layoutParams.verticalBias = (float) 0.95;
layoutParams.horizontalBias = (float) 0.5;
circleImageView.setLayoutParams(layoutParams);
答案 2 :(得分:0)
ConstraintLayout cLayout = findViewById(R.id.main_layout);
TextView ev = new TextView(getApplicationContext());
ev.setText(getString(R.string.not_found_name));
ev.setTextSize(50);
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT);
layoutParams.bottomToBottom = ConstraintSet.PARENT_ID;
layoutParams.endToEnd = ConstraintSet.PARENT_ID;
layoutParams.startToStart = ConstraintSet.PARENT_ID;
layoutParams.topToTop = ConstraintSet.PARENT_ID;
ev.setLayoutParams(layoutParams);
cLayout.addView(ev);