简体   繁体   中英

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:

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 . 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 . Does this mean that I can't call the width method inside the onCreate method? And is there a way around this?

Does this mean that I can't call the width method inside the onCreate method?

You can call width() . However, relative1.getWidth() will be 0 at this point, because the layout has not been measured and laid out yet.

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 . For example, ConstraintLayout and LinearLayout both support sizing things based upon fractions, without you having to do the calculations yourself.

If you are sure that you need the width and height, wait to try using it until the widgets have been sized .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM