Roy
Roy

Reputation: 45

Moving an ImageView according to gravity?

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!

Upvotes: 2

Views: 867

Answers (2)

LOG_TAG
LOG_TAG

Reputation: 20569

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

Upvotes: 1

TheIT
TheIT

Reputation: 12219

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.

Upvotes: 1

Related Questions