Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何设置ImageView';s在约束布局中的动态位置_Android_Android Studio 2.3_Android Constraintlayout - Fatal编程技术网

Android 如何设置ImageView';s在约束布局中的动态位置

Android 如何设置ImageView';s在约束布局中的动态位置,android,android-studio-2.3,android-constraintlayout,Android,Android Studio 2.3,Android Constraintlayout,我在一个约束布局中动态创建了ImageView。运行应用程序后,ImageView将显示在左上角,因为没有为ImageView定义位置。 如何动态设置ImageView的位置(比如说中心位置) 我已经写了下面的代码 ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout); ImageView imageView = new ImageView(ChooseOptionsActivity.t

我在一个约束布局中动态创建了ImageView。运行应用程序后,ImageView将显示在左上角,因为没有为ImageView定义位置。 如何动态设置ImageView的位置(比如说中心位置)

我已经写了下面的代码

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);

ImageView imageView = new ImageView(ChooseOptionsActivity.this);
imageView.setImageResource(R.drawable.redlight);

layout.addView(imageView);

setContentView(layout);

非常感谢您的建议。

您需要使用应用于
ImageView
ConstraintSet
将其居中。可以找到
ConstraintSet
的文档

此类允许您以编程方式定义一组约束以与ConstraintLayout一起使用。它允许您创建和保存约束,并将其应用于现有的ConstraintLayout。ConstraintSet可以通过多种方式创建

也许这里最棘手的事情是视图如何居中。对定心技术的良好描述如下

对于您的示例,以下代码就足够了:

    // Get existing constraints into a ConstraintSet
    ConstraintSet constraints = new ConstraintSet();
    constraints.clone(layout);
    // Define our ImageView and add it to layout
    ImageView imageView = new ImageView(this);
    imageView.setId(View.generateViewId());
    imageView.setImageResource(R.drawable.redlight);
    layout.addView(imageView);
    // Now constrain the ImageView so it is centered on the screen.
    // There is also a "center" method that can be used here.
    constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
            0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP,
            0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
    constraints.applyTo(layout);