以编程方式将视图添加到约束布局跳转到原点

问题描述 投票:0回答:1

我正在用安卓做一些动画,我在足球场里有球员。对于一些我想添加标签的元素,添加一些约束以将它们与各自的视图分组,并且当动画开始时标签会跟随它们。

我试过这两种解决方案,但文本视图一直跳到约束布局的原点:

如何以编程方式向 ConstraintLayout 添加视图和约束?

在 ConstraintLayout 中以编程方式添加视图

我已经为这些解决方案尝试了很多变体,但没有成功。我当然遗漏了一些东西......任何想法将不胜感激!

我创建视图的代码:

   //init imageview
                ImageView imageView = new ImageView(this);
                imageView.setId(View.generateViewId());
                imageView.setTag(key);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                //buscar el drawable correspondiente
                imageView.setImageDrawable(setViewDrawable(vista));
                imageView.setOnLongClickListener(this);
//set width and height of the view
                Pair<Integer, Integer> widthAndHeight = getWidthAndHeight(key);
                //set ancho y alto
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(widthAndHeight.first, widthAndHeight.second);
                imageView.setLayoutParams(params);
                mTacticLayout.addView(imageView);
                //set position
                if (!isEdit) {
                    Pair<Float, Float> xAndY = getViewXY(key);
                    Float rotation = getViewRotation(key);
                    //account for offsets
                    imageView.setX(xAndY.first - widthAndHeight.first / 2);
                    imageView.setY(xAndY.second - widthAndHeight.second / 2);
                    imageView.setRotation(rotation);
                }

//HERE HERE HERE LOOK AT ME  
       if(imageView.getTag().toString().equals(r.getString(R.string.ball_tag))){
                    TextView textView = new TextView(this);
                    textView.setId(View.generateViewId());
                    textView.setText("My View");

                    mTacticLayout.addView(textView);
                    ConstraintSet set = new ConstraintSet();
                    set.clone(mTacticLayout);
                    set.connect(textView.getId(), ConstraintSet.TOP, imageView.getId(), ConstraintSet.BOTTOM, 0);
                    set.connect(textView.getId(), ConstraintSet.RIGHT, imageView.getId(), ConstraintSet.RIGHT, 0);
                    set.connect(textView.getId(), ConstraintSet.LEFT, imageView.getId(), ConstraintSet.LEFT, 0);
                    set.applyTo(mTacticLayout);
                }
java android android-constraintlayout
1个回答
0
投票

setX()
根据 documentation 执行以下操作:

设置此视图的视觉 x 位置,以像素为单位。这相当于将 translationX 属性设置为传入的 x 值与当前 left 属性之间的差值。

setTranslationX()
也根据文档这样做:

设置此视图相对于其左侧位置的水平位置。除了对象的布局放置它的位置之外,这有效地定位对象后布局。

setY()
setTranslationY()
对 y 坐标做同样的事情。

这里的关键词是post-layout。您的

ImageView
被放置在顶部/左侧,因为它没有约束。
TextView
根据其约束被放置在
ImageView
上,所以它也被放置在顶部/左侧。现在两个视图都布置在顶部/左侧,
ImageView
根据
setX()
setY()
移动,将
TextView
留在后面。

有几种方法可以解决这个问题。可能最简单的方法是将应用于

ImageView
的相同翻译应用于
TextView
.

© www.soinside.com 2019 - 2024. All rights reserved.