[英]Can other methods from a java file be called in the onCreate method in Android Studio?
I'm trying to call a method that is defined later in my java file: 我正在尝试调用稍后在我的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);
}
However, when I run my app in debug mode I see that moveHorizontal
and moveVertical
are both set to 0
. 但是,当我在调试模式下运行我的应用程序时,我看到moveHorizontal
和moveVertical
都设置为0
。 I know the method works fine as I've tried using it in the rest of the code to find width(1f/12f)
and it returns 90
. 我知道该方法工作正常,因为我尝试在其余代码中使用它来查找width(1f/12f)
并返回90
。 Does this mean that I can't call the width
method inside the onCreate
method? 这是否意味着我无法在onCreate
方法中调用width
方法? And is there a way around this? 有没有办法解决这个问题?
Does this mean that I can't call the width method inside the onCreate method? 这是否意味着我无法在onCreate方法中调用width方法?
You can call width()
. 你可以调用width()
。 However, relative1.getWidth()
will be 0 at this point, because the layout has not been measured and laid out yet. 但是, relative1.getWidth()
将为0,因为尚未测量和布局布局。
And is there a way around this? 有没有办法解决这个问题?
First, see if there is a better solution to whatever problem you are trying to solve, that involves getting the size of relative1
. 首先,看看是否有更好的解决方案来解决您要解决的任何问题,包括获取relative1
的大小。 For example, ConstraintLayout
and LinearLayout
both support sizing things based upon fractions, without you having to do the calculations yourself. 例如, ConstraintLayout
和LinearLayout
都支持基于分数的大小调整,而无需您自己进行计算。
If you are sure that you need the width and height, wait to try using it until the widgets have been sized . 如果您确定需要宽度和高度,请等待尝试使用它,直到小部件的大小 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.