【发布时间】:2020-03-27 09:28:12
【问题描述】:
我正在制作一些游戏以了解有关 Java 和 AStudio 的更多信息。我需要将一个视图居中到另一个视图。两个视图都是 ConstraintLayouts。我已经尝试过 MATCH_PARENT 或 WRAP_CONTENT 以及更改大小,但较小的视图将始终包裹到父视图中的 0,0 位置。如果我在子视图上使用“setX/setY”,它会在父视图还是主视图布局上工作?无论如何,我知道它是一个 android 视图属性,可以使用重力或 smth 以某种方式使孩子居中,但我在任何地方都找不到正确的答案。
public class GameField extends ConstraintLayout {...
public class GameUnit extends ConstraintLayout {...
...
...
private void deployClick(){
int sizeUnit = 960/boardSizeX;
int x = 4;
for (int i =0; i<x;i++){
int randCounter = randomNum.nextInt(counterFields);
counterUnits++;
gameUnit[counterUnits] = new GameUnit(this,randomNum.nextInt(4),randomNum.nextInt(10),randomNum.nextInt(10));
gameUnit[counterUnits].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
gameUnit[counterUnits].setLayoutParams(new android.view.ViewGroup.LayoutParams(sizeUnit-5,sizeUnit-5));
gameField[randCounter].addView(gameUnit[counterUnits]);
gameField[randCounter].setUnitAdded(true);
deployClicked = true;
}
}
【问题讨论】:
-
我刚刚检查了 setX/Y 方法,这些方法适用于父级,但必须有另一种方法。我想避免额外的位置计算,尤其是当一切都是动态的。