【发布时间】:2018-07-21 16:37:36
【问题描述】:
我正在用 android 制作一些动画,并且我在足球场内有球员。对于一些我想添加标签的元素,添加一些约束以将它们与它们各自的视图分组,并且当动画开始时,标签会跟随它们。
我已经尝试了这两种解决方案,但是 textview 一直跳到约束布局的原点:
How to programmatically add views and constraints to a ConstraintLayout?
Add a view programmatically in 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);
}
【问题讨论】:
-
这有点困难,但在 XML 中定义一个组并通过代码查看该组视图
标签: java android programmatically android-constraintlayout