我怎样才能调用onMeasure方法? - Android

时间:2014-05-21 16:41:33

标签: java android onmeasure

我有一个视图的活动。此视图的目的是显示平方网格。方形边将等于屏幕宽度除以水平存在的方格数。

@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();
}

我已经很难创建一个自定义高度的视图,我这样做了:

@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();
}

问题是,当我调试时,squareSide变量的值为0.我认为可能在createGuideLines()之后调用onMeasure()。如果我之前打过电话,会解决我的问题吗?我在文档中读到有一个调用onMeasure()方法的方法requestLayout(),但我不知道如何实现它。

感谢您的时间。

3 个答案:

答案 0 :(得分:3)

invalidate()会导致View及其相交的Views通过调用各自的onDraw()来重绘自己。

另一方面,requestLayout()会使View自行调整大小。这两个过程是相互独立的; requestLayout()不会调用invalidate(),反之亦然。

在您的情况下,您可以致电requestLayout(),因为您只处理测量。

答案 1 :(得分:2)

requestLayout电话添加到您的createLayout方法

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

答案 2 :(得分:2)

我建议您在onCreate()方法中执行此操作:

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