Java / Android:将onSensorChanged方法的加速度计值传递给onCreateSetContentView()

时间:2012-06-12 12:19:04

标签: java android

我是Java和Android编程语言的新手,这是我研究的第一个平台。 我想问一下,如何在这个方法中访问event.values [1]?

public void onSensorChanged(SensorEvent event) {synchronized (this){
    if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)

        return;
    mAccVals.x = (float) (event.values[1] * FILTERING_FACTOR + mAccVals.x * (1.0 - FILTERING_FACTOR));
    //mAccVals.y = (float) ((-event.values[1] * FILTERING_FACTOR + mAccVals.y * (1.0 - FILTERING_FACTOR)));
    mAccVals.z = (float) (event.values[2] * FILTERING_FACTOR + mAccVals.z * (1.0 - FILTERING_FACTOR));

    scene.camera().position.x = mAccVals.x * .2f;
    scene.camera().position.z = mAccVals.z * .8f;

    scene.camera().target.x = -scene.camera().position.x;
    scene.camera().target.z = -scene.camera().position.z;

}

我想获取event.values [1],然后将其显示在textview

protected void onCreateSetContentView()
{   
    setContentView(R.layout.custom_layout_example); 
        LinearLayout ll = (LinearLayout) this.findViewById(R.id.scene1Holder);
        ll.addView(_glSurfaceView);
        TextView myTextView = (TextView) findViewById(R.id.splashTitle); 
        myTextView.setText("Test " + event.values[1]  );
        return;                  
 }

有什么建议我该如何解决这个问题? 提前致谢

1 个答案:

答案 0 :(得分:1)

Activity中创建一个字段,并将其分配给您的R.id.splashTitle

TextView mTextView;
...
protected void onCreateSetContentView() {
    mTextView = (TextView) findViewById(R.id.splashTitle);
    ...
}

然后在onSensorChanged()中设置文本,如下所示:

public void onSensorChanged(SensorEvent event) {
    mTextView.setText("Test " + event.values[1]);
    ...
}

或者您可以将最新传感器的值存储在字段中:

// Class field
float[] mSensorValues;
// In onSensorChanged()
mSensorValues = event.values;
// In onCreateSetContentView()
myTextView.setText("Test " + mSensorValues[1]);

要保留onCreateonSensorChanged的正确顺序,您可以使用documentation中描述的方法:

protected void onResume() {
     super.onResume();
     mSensorManager.registerListener(this, mAccelerometer,
                                     SensorManager.SENSOR_DELAY_NORMAL);
 }

 protected void onPause() {
     super.onPause();
     mSensorManager.unregisterListener(this);
 }