我有一个应用程序,我想在点击按钮时启动加速度计的监听器,所以我尝试了这样:
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)"
有没有办法轻松解决?我是否必须覆盖任何其他方法?感谢
答案 0 :(得分:2)
您需要使用MyActivity.this
,因为this
引用OnClickListener
而registerListener
方法需要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);
}
});
}