【问题标题】:cannot place view programatically using ConstraintLayout无法使用 ConstraintLayout 以编程方式放置视图
【发布时间】:2017-07-01 03:56:16
【问题描述】:

我有一个约束布局,它有一个类似于射箭目标的图像视图。在触摸事件中,我试图在用户按下目标的位置放置另一个图像(子弹)。但是,我只能调整正确的图像的顶部对齐方式,但我根本无法水平调整视图。它总是最终调整到左边。做错了什么?坐标工作 100% 正常,我什至尝试对值进行硬编码,但没有运气。

 target.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Matrix inverse = new Matrix();
            imageView.getImageMatrix().invert(inverse);
            float[] touchPoint = new float[]{event.getX(), event.getY()};
            inverse.mapPoints(touchPoint);
            int x = (int) touchPoint[0];
            int y = (int) touchPoint[1];

            ConstraintSet set = new ConstraintSet();
            ImageView view = new ImageView(this);
            ConstraintLayout.LayoutParams vp =
                new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.drawable.bullet);
            view.setImageBitmap(bm);
            layout.addView(view, 7, vp);
            set.clone(layout);
            set.connect(view.getId(), ConstraintSet.TOP,
            target.getId(), ConstraintSet.TOP, (int) y - 60);
            set.connect(view.getId(), ConstraintSet.LEFT, target.getId(), ConstraintSet.LEFT, (int) x);
            set.applyTo(layout);

        }
    });

【问题讨论】:

  • 查看更新的答案和解决方案。

标签: android android-constraintlayout


【解决方案1】:

您可能会遇到这个问题: 62154545 ConstraintSet connect ignores right and left margins

当使用 ConstraintSet#connect 将 TextView 添加到 XML 中定义的空 ConstraintLayout 时,左右边距被忽略(为零),而顶部和底部边距被尊重。 TextView 的高度和宽度都设置为“MATCH_CONSTRAINT”。请参阅以下代码和屏幕截图。当一切都在 XML 中设置时,这可以正常工作。


刚刚又看了一遍。使用ConstraintSet.STARTConstraintSet.END 而不是ConstraintSet.LEFTConstraintSet.RIGHT。我刚试了一下,它工作正常。我不能说为什么左右不起作用。

【讨论】:

  • 谢谢你,我会试试看。我最终使用相对布局来紧急解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多