繁体   English   中英

Android:CustomView应该对方向做出反应时是静态的

[英]Android: CustomView is static when it is supposed to react to orientation

在我的应用程序中,我有一个基本的指南针,它在“ compassView”类中呈现。 如果我在这样的Display Compass活动中设置contentView,则如下所示: compassView = new CompassView(this); setContentView(compassView); 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();
      }

    } 

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

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

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

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

setContentView(R.layout.activity_display_compass);
compassView = (CompassView)findViewById(R.id.compassView);  // <- missing?!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM