您可以在Android的自定义视图中使用SensorEventListener吗?
问题描述:
我想创建一个自定义视图,其中位图随着手机的移动而移动。您可以在Android的自定义视图中使用SensorEventListener吗?
所以我创建的自定义视图和实施sensorEventListener:
public class MovingStarView extends View implements SensorEventListener {
private SensorManager sm;
private Sensor mAccelerometer;
.....Other Initialization stuff.....
private void initSensor(){
// Get an instance of the SensorManager
sm = (SensorManager) getSystemService(SENSOR_SERVICE); <---NOT RESOLVED
//Get the Accelerometor
mAccelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
Eclipse是说SENSOR_SERVICE不能得到解决。我应该以不同的方式调用吗?
是否有可能这样做,或者我将不得不对侦听调用自定义视图的Activity进行侦听?
答
您需要在您的视图中使用context
对象。 然后致电sm = (SensorManager) context.getSystemService(context.SENSOR_SERVICE)
答
尝试导入android.content.Context
也可以尝试Context.SENSOR_SERVICE通过Context命名空间来访问它。
是的,你应该能够让你的视图使用SensorEventListener。你的View对象可以实现你想要的任意数量的接口:)(尽管从对象设计的角度来看,你可能想避免这种情况)。