1

我有一个应用程序,我想在单击按钮时启动加速度计的侦听器,所以我尝试了这种方式:

private SensorManager sensorManager;

@Override
public void onCreate (Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView(R.layout.storing_act);

    Button start = (Button)findViewById(R.id.startl);

    start.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
            sensorManager.registerListener(this, 
                    sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
    });

但它出现了一条消息

“ SensorManager 类型中的方法 registerListener(SensorEventListener, Sensor, int) 不适用于参数 (new View.OnClickListener(){}, Sensor, int)”

有没有办法轻松解决?我是否必须覆盖任何其他方法?谢谢

4

1 回答 1

2

你需要使用MyActivity.this因为this引用OnClickListenerregisterListener方法是期望的SensorEventListener

public class MyActivity extends Activity implements SensorEventListener {
    @Override
    public void onCreate (Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.storing_act);

        Button start = (Button)findViewById(R.id.startl);

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
                sensorManager.registerListener(MyActivity.this, 
                        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                        SensorManager.SENSOR_DELAY_NORMAL);
            }
        });
}
于 2013-04-10T14:23:33.093 回答