2012-01-08 73 views
1

我想創建一個自定義視圖,其中位圖隨着手機的移動而移動。您可以在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進行偵聽?

回答

4

您需要在您的視圖中使用context對象。 然後致電
sm = (SensorManager) context.getSystemService(context.SENSOR_SERVICE)

2

嘗試導入android.content.Context

也可以嘗試Context.SENSOR_SERVICE通過Context命名空間來訪問它。

是的,你應該能夠讓你的視圖使用SensorEventListener。你的View對象可以實現你想要的任意數量的接口:)(儘管從對象設計的角度來看,你可能想避免這種情況)。

相關問題