【问题标题】:Can other methods from a java file be called in the onCreate method in Android Studio?可以在 Android Studio 的 onCreate 方法中调用 java 文件中的其他方法吗?
【发布时间】:2017-04-26 19:28:33
【问题描述】:

我正在尝试调用稍后在我的 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。这是否意味着我不能在onCreate 方法中调用width 方法?有没有办法解决这个问题?

【问题讨论】:

  • 你试过调试吗?在我看来,relative1.getWidth() 返回一个意外值的可能性更大(也许它还没有绘制?)

标签: java android variables methods oncreate


【解决方案1】:

这是否意味着我不能在onCreate方法内部调用width方法?

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

有没有办法解决这个问题?

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2015-08-08
    • 1970-01-01
    相关资源
    最近更新 更多