1

在我的应用程序中,我有一个基本的指南针,它在“compassView”类中呈现。如果我在我的 Display Compass 活动中设置 contentView,如下所示:compassView = new CompassView(this); setContentView(compassView);它工作正常并指向北方,但是如果我将内容视图设置为 setContentView(activity_display_compass)它将呈现指南针和我可能拥有的任何文本视图,但指南针是静态的;即针不动。我不知道是什么原因造成的。任何指导将不胜感激?

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

    <com.example.gpsfinder.CompassView
        android:id="@+id/compassView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

显示指南针活动

public class DisplayCompass extends Activity {

      private static SensorManager sensorService;
      private CompassView compassView;
      private Sensor  sensorAccelerometer;
      private Sensor  sensorMagnetometer;

      private float [] lastAccelerometer = new float[3];
      private float [] lastMagnetometer = new float[3];
      private boolean  lastAccelerometerSet = false;
      private boolean lastMagnetometerSet = false;

      private float[] rotation = new float[9];
      private float[] orientation = new float[3];


    /** Called when the activity is first created. */

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        compassView = new CompassView(this);
        setContentView(compassView);

        sensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensorAccelerometer = sensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorMagnetometer = sensorService.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        //sensor = sensorService.getDefaultSensor(Sensor.TYPE_ORIENTATION);

        if (sensorAccelerometer != null &&  sensorMagnetometer != null) {
          sensorService.registerListener(mySensorEventListener, sensorAccelerometer,
              SensorManager.SENSOR_DELAY_UI);
          sensorService.registerListener(mySensorEventListener, sensorMagnetometer,
                  SensorManager.SENSOR_DELAY_UI);
          Log.i("Compass MainActivity", "Registerered for ORIENTATION Sensor");

        } else {
          Log.e("Compass MainActivity", "Registerered for ORIENTATION Sensor");
          Toast.makeText(this, "ORIENTATION Sensor not found",
              Toast.LENGTH_LONG).show();
          finish();
        }
      }

      private SensorEventListener mySensorEventListener = new SensorEventListener() {


        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }


        public void onSensorChanged(SensorEvent event) {
            if(event.sensor == sensorAccelerometer){
                System.arraycopy(event.values,0,lastAccelerometer, 0,event.values.length);
                lastAccelerometerSet= true;
            }
            else if (event.sensor == sensorMagnetometer){
                System.arraycopy(event.values,0,lastMagnetometer, 0,event.values.length);
                lastMagnetometerSet = true;
            }
            if(lastAccelerometerSet && lastMagnetometerSet)
                SensorManager.getRotationMatrix(rotation,null,lastAccelerometer ,lastMagnetometer );
                SensorManager.getOrientation(rotation,orientation);
          // angle between the magnetic north direction
          // 0=North, 90=East, 180=South, 270=West
          double azimuth = Math.toDegrees(orientation[0]);
          compassView.updateDirection(azimuth);
        }
      };

      @Override
      protected void onDestroy() {
        super.onDestroy();
          sensorService.unregisterListener(mySensorEventListener);

      }
}

指南针视图

public class CompassView extends View{

     private Paint paint;
      private double position = 0;

      public CompassView(Context context) {
        super(context, null);
        init();
      }

      public CompassView(Context context, AttributeSet attrs) {
            super(context,attrs, 0);
            init();
      }

      public CompassView(Context context, AttributeSet attrs,int defStyle) {
            super(context,attrs, defStyle);
            init();
      }



      private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setTextSize(25);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);
      }

      @Override
      protected void onDraw(Canvas canvas) {
        int xPoint = getMeasuredWidth() / 2;
        int yPoint = getMeasuredHeight() / 2;

        float radius = (float) (Math.max(xPoint, yPoint) * 0.6);
        canvas.drawCircle(xPoint, yPoint, radius, paint);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);

        // 3.143 is a good approximation for the circle
        canvas.drawLine(xPoint,
            yPoint,
            (float) (xPoint + radius
                * Math.sin((double) (-position) / 180 * 3.143)),
            (float) (yPoint - radius
                * Math.cos((double) (-position) / 180 * 3.143)), paint);

        canvas.drawText(String.valueOf(position), xPoint, yPoint, paint);
      }

      public void updateDirection(double azimuth) {
        this.position = azimuth;
        invalidate();
      }

    } 
4

1 回答 1

2

您的问题很简单,当您第一次编写应用程序时,您正在以编程方式创建您CompassView的:

    compassView = new CompassView(this);
    setContentView(compassView);

当您更改为使用 XML 布局时,第一行可能已被删除。但是,您仍然需要分配您的compassView成员变量,因为您在SensorEventListener'sonSensorChanged()方法中使用它。你得到了一个NullPointerException(你可以通过查看LogCat看到)。

因此,在您的onCreate()方法中,设置内容视图后,请记住执行以下操作:

setContentView(R.layout.activity_display_compass);
compassView = (CompassView)findViewById(R.id.compassView);  // <- missing?!
于 2013-06-04T22:47:39.783 回答