可以在Android Studio的onCreate方法中调用java文件中的其他方法吗?

时间:2016-12-11 23:23:00

标签: java android variables methods oncreate

我试图调用稍后在我的java文件中定义的方法:

public int moveHorizontal;
public int moveVertical;
public RelativeLayout relative1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    relative1 = (RelativeLayout) findViewById(R.id.relative1);
    moveHorizontal = width(1f/12f);
    moveVertical = height(1f/12f);
}

...

public int width(float fraction) {
    float relativeWidth = relative1.getWidth();
    return Math.round(fraction*relativeWidth);
}

但是,当我在调试模式下运行我的应用时,我发现moveHorizontalmoveVertical都设置为0。我知道该方法运行正常,因为我已尝试在其余代码中使用它来查找width(1f/12f)并返回90。这是否意味着我无法在width方法中调用onCreate方法?有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:3)

  

这是否意味着我无法在onCreate方法中调用width方法?

您可以致电width()。但是,relative1.getWidth()此时将为0,因为布局尚未测量和布局。

  

还有办法解决这个问题吗?

首先,看看是否有更好的解决方案来解决您要解决的任何问题,这需要获得relative1的大小。例如,ConstraintLayoutLinearLayout都支持基于分数的大小调整,而无需您自己进行计算。

如果您确定需要宽度和高度wait to try using it until the widgets have been sized