2

I understand that I cannot get the dimensions too early before the UI has been set up.

I know I have to get the dimensions after the onCreate().

But even if I do the following, they still always return me 0.

onCreate():

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_path);
        ...
        onCreateDone = true;
    }

I hope to get the dimensions in onSensorChanged()

    // called when sensor values change
    public void onSensorChanged(SensorEvent event) { // is roughly called 350 times in 1s

        if (layoutSizeNotObtained && onCreateDone) { // only runs once to get the layout size
            RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_show_path_relativelayout);
            int layoutWidth = relativeLayout.getWidth();
            int layoutHeight = relativeLayout.getHeight();
            Log.d("ShowPathActivity", "layout size: " + layoutWidth + " " + layoutHeight);

            Constant.setInitialX(layoutWidth / 2);
            Constant.setInitialY(layoutHeight / 2);
            layoutSizeNotObtained = false;
        }

        ....
    }

Where goes wrong?

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174

2 Answers2

2

The issue is that there's no warranty, that layout is done during onSensorChanged(SensorEvent event) call. Views are measured only during first layout and it's done some time after onCreate(), but not during it or immediately after.

I would suggest to use this suggestion via ViewTreeObserver.

Community
  • 1
  • 1
sandrstar
  • 12,503
  • 8
  • 58
  • 65
  • Where should I add the snippet? I added it into the constructor of my custom view. I saw the method keeps being called. I wish it to be called only once. – Sibbs Gambling Jul 15 '13 at 04:14
  • You can call it from onCreate() of your custom view. It called every layout, but You can call removeGlobalOnLayoutListener() so it won't be called further. – sandrstar Jul 15 '13 at 04:22
  • I am really a newbie to this. Here is my custom view. I didn't see onCreate(). Where should I put it? http://pastie.org/private/70tuepnuj59ajtbtesgkg – Sibbs Gambling Jul 15 '13 at 05:02
  • Meant onCreate() of the activity, the one provided in Your question. – sandrstar Jul 15 '13 at 05:11
  • Awesome! it works now. I have marked this as the answer. Could you please roughly tell me what the snippet does? It would be nice for the future programmers too. :D – Sibbs Gambling Jul 15 '13 at 05:24
  • 1
    'A view tree observer is used to register listeners that can be notified of global changes in the view tree', basically, I think all explanations provided in referenced question. – sandrstar Jul 15 '13 at 05:32
0

Are you calling the setContentView function in onCreate? If not, you need to.

Rob K
  • 294
  • 2
  • 10