Search code examples
javaandroidonmeasure

How can I invoke onMeasure method? - Android


I have one activity with one view. The purpose of this view is to show a squared grid. The square sides will equal to the screen width divided by the number of squares that exist horizontally.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getValues();
    createLayout();
}

public static int top;
public static int side;

private void getValues() {
    top = 5; //squares horizontally
    side = 6; //squares vertically
}

private void createLayout() {
    BoardView bv = new BoardView(this);
    bv.setBackgroundColor(Color.BLUE);
    setContentView(bv);
    bv.createGuideLines();
}

I already struggled to create a view with custom height, I did this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    squareSide = MeasureSpec.getSize(widthMeasureSpec)/top;
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),squareSide*side);
}

public void createGuideLines() {
    for(int c = 1; c<=side; ++c) {
        path.moveTo(c*squareSide, 0);
        path.lineTo(c*squareSide, squareSide*top);
    }
    for(int l = 1; l<=side; ++l) {
        path.moveTo(0, l*squareSide);
        path.lineTo(side*squareSide, l*squareSide);
    }
    invalidate();
}

The problem is, when I debug, squareSide variable has value 0. I tought that maybe onMeasure() is being called after createGuideLines(). If I called it before, would it solve my problem? I read on the documentation that there is a method requestLayout() that calls onMeasure() method, but I have no clue on how to implement it.

Thanks for your time.


Solution

  • I suggest to you to do this, in onCreate() method :

    Display display = getWindowManager().getDefaultDisplay();
    int squareSide = (int) Math.floor(display.getWidth() / top);