1

我有这个问题要问你:

我写了这段代码:

public class MainActivity extends Activity implements SensorEventListener {
    private SensorManager mSensorManager;
    private Sensor mSensor;
    ArrayList<String> oldvalue  = new ArrayList<String>();
    int count;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener((SensorEventListener) this, mSensor,         SensorManager.SENSOR_DELAY_NORMAL);
        count = 0;
        //oldvalue = null;

    }

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

    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void onSensorChanged(SensorEvent event) {
        String x,y,z;
        Float xnum,ynum,znum;
        TextView xtextview,ytextview,ztextview = new TextView(this);

        if (oldvalue == null || oldvalue.size()<1) {
        String statoarray = "null or 0";
        Toast.makeText(this, statoarray, Toast.LENGTH_SHORT)
          .show();
        }
        else {
            String statoarray = String.valueOf(oldvalue.size());
            Toast.makeText(this, statoarray, Toast.LENGTH_SHORT)
              .show();
        }


        if (oldvalue.size()<2) 
        {
            xtextview=(TextView)findViewById(R.id.x); 
            ytextview=(TextView)findViewById(R.id.y);
            ztextview=(TextView)findViewById(R.id.z);

            xnum = event.values[0];
            ynum = event.values[1];
            znum = event.values[2];

            oldvalue.add(String.valueOf(xnum));
        oldvalue.add(String.valueOf(ynum));
        oldvalue.add(String.valueOf(znum));


        x = Float.toString(Math.round(xnum));
        y = Float.toString(Math.round(ynum));;
        z = Float.toString(Math.round(znum));;

        xtextview.setText(x);
        ytextview.setText(y);
        ztextview.setText(z);   
        }

        //Toast.makeText(this, "pieno", Toast.LENGTH_SHORT)
        //.show();
    }


}

所以我不明白,因为每次改变 xyz 的值时,数组都会重新初始化......

我有必要在数组中存储更多的 cicle 值

非常感谢

4

1 回答 1

1

因为你在里面初始化它们onSensorChanged()

所以当设备移动很少时,onSensorChanged()被调用并且所有

 String x,y,z;
        Float xnum,ynum,znum;
        TextView xtextview,ytextview,ztextview = new TextView(this);

这些以及其他初始化的东西onSensorChanged()reinitialized

so Declare these inside class

并使用该类中的任何位置

于 2013-08-07T19:06:53.890 回答