2

I am trying to make an ImageView move according to however the user tilts the device. I'm still learning in Android development so i don't know much about Sensors. I have tried using this but i'm not sure what to do afterwards but I'm guessing that I'm on the right track.

ImageView image = (ImageView) findViewById(R.id.image);
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor mSensor =  mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);

Any tips would help Thank you!

Roy
  • 45
  • 6

2 Answers2

1

You'll want to create and register a SensorListener:

mSensorManager.registerListener(mSensorListener, sensor, SensorManager.SENSOR_DELAY_GAME);

Then in the SensorListener's onSensorChanged(SensorEvent event) method, get the sensor readings from the event.values array.

This will get you the gravity values, which you then use to move the ImageView.

As for how to move the ImageView, it depends a lot on what sort of Layout the view is in, but you could play around with setting the ImageView's margins.

TheIT
  • 11,919
  • 4
  • 64
  • 56
1

Have a look at this SO question for more understanding about gravity.

Try to learn how compass works bye this example

I guess your looking for solution

ImageView move according to however the user tilts the device

which is exactly look like this accelerometer example

enter image description here

Community
  • 1
  • 1
LOG_TAG
  • 19,894
  • 12
  • 72
  • 105
  • Thank you very much! I will try this right away Another question, is there a way to test this on the Eclipse Emulator? or i would have to try it on an actual phone? – Roy Feb 12 '14 at 00:47
  • @user3097181 better try with Device otherwise you need to do this http://code.google.com/p/openintents/wiki/SensorSimulator – LOG_TAG Feb 12 '14 at 05:35