java - 如何调用 onMeasure 方法? - 安卓

标签 java android onmeasure

我有一项 Activity 和一种 View 。此 View 的目的是显示方形网格。正方形边长等于屏幕宽度除以水平存在的正方形数量。

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

我已经很难创建具有自定义高度的 View ,我这样做了:

@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。我认为 onMeasure() 可能是在 createGuideLines() 之后调用的。如果我之前调用它,可以解决我的问题吗?我在文档中看到有一个方法 requestLayout() 调用 onMeasure() 方法,但我不知道如何实现它。

感谢您的宝贵时间。

最佳答案

requestLayout 调用添加到 createLayout 方法

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

关于java - 如何调用 onMeasure 方法? - 安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789206/

相关文章:

android - 在 Android Spinner 中设置文本颜色

android - 为什么在我的自定义 View 中调用了两次 onMeasure()?

Android MediaRecorder 错误(1, -2147483648)

Android:自定义 View 在错误的 x、y 坐标处绘制

android - 在 onResume() 之前动态更改 DialogFragment Max_Height?

java - 如何在本地使用 spring-cloud-starter-aws 运行应用程序?

java - Tomcat - 图像不显示

java - Netbeans 不会在“项目”选项卡中显示 Web 项目

java - Google App Engine (GAE/J) 上的 Spring 和任务队列问题。任务正在运行,无需等待

android - 在两个 Kotlin 中拆分字符串