Karol Odwald
Karol Odwald

Reputation: 53

How do I programmatically center a view on the layout?

I am makig some game to learn more about Java and AStudio. I need to center one view onto another view. Boths views are ConstraintLayouts. I've already tried MATCH_PARENT or WRAP_CONTENT along with changing the size but the smaller view will always wrap to 0,0 position in parent view. If I use "setX/setY" on the child view, will it work on the parent view or the main view Layout? Anyways I know its an android view attribute to center the child somehow using gravity or smth but I couldn't find the correct answer anywhere.

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;
        }
    }

Upvotes: 1

Views: 209

Answers (1)

B&#246; macht Blau
B&#246; macht Blau

Reputation: 13009

Rule of thumb for LayoutParams: they are named after the parent layout. So for the inner custom View you need to set ConstraintLayout.LayoutParams:

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

Since your outer custom View extends from ConstraintLayout, you can use a ConstraintSet to position the inner View correctly. They use View id's so you need to give your dynamically added Views an id by calling setId(View.generateViewId()) on them. Then you can proceed as follows:

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);

First add the unit View to the field View, then call

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

Upvotes: 1

Related Questions