1

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?

Thomas Doyle
  • 113
  • 13
  • 2
    Have you tried debugging? Seems more likely to me that `relative1.getWidth()` is returning an unexpected value (perhaps it is not drawn yet?) – John3136 Dec 11 '16 at 23:27

1 Answers1

3

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.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491