簡體   English   中英

如何以編程方式將視圖居中放置在布局上?

[英]How do I programmatically center a view on the layout?

我正在制作一些游戲以了解有關 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;
        }
    }

LayoutParam的經驗法則:它們以父布局命名。 因此,對於內部自定義View您需要設置ConstraintLayout.LayoutParams

ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(sizeUnit - 5, sizeUnit - 5);
gameUnit[counterUnits].setLayoutParams(lp);
gameField[randCounter].addView(gameUnit[counterUnits]);

由於您的外部自定義ViewConstraintLayout擴展,您可以使用ConstraintSet正確定位內部View 它們使用View id,因此您需要通過對它們調用setId(View.generateViewId())來為動態添加的View一個 id。 然后您可以按照以下步驟進行:

int unitId = gameUnit[counterUnits].getId();
int fieldId = gameField[randCounter].getId();

ConstraintSet cs = new ConstraintSet();
cs.connect(unitId, ConstraintSet.START, fieldId, ConstraintSet.START)
cs.connect(unitId, ConstraintSet.END, fieldId, ConstraintSet.END)
cs.connect(unitId, ConstraintSet.TOP, fieldId, ConstraintSet.TOP)
cs.connect(unitId, ConstraintSet.BOTTOM, fieldId, ConstraintSet.BOTTOM)
cs.constrainHeight(unit.id, lp.height);
cs.constrainWidth(unit.id, lp.width);

首先將單元View添加到字段View ,然后調用

cs.applyTo(gameField[randCounter])   
gameField[randCounter].setUnitAdded(true)
deployClicked = true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM