简体   繁体   中英

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.

invalidate() will cause the View and the Views it intersects to redraw themselves by, among other things, calling their respective onDraw() .

In the other hand, requestLayout() will make the View resize itself. This two processes are independent of one another; requestLayout() will not call invalidate() and vice versa.

In your case you can call requestLayout() since you are only dealing with measurements.

add the requestLayout call to your createLayout method

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM