0

我必须提出一个指南针指示西点的应用程序。这是我的代码

public class CustomCompassActivity extends Activity implements SensorEventListener {

Float azimut;  // View to draw a compass

public class CustomDrawableView extends View {
Paint paint = new Paint();
TextView t1;

public CustomDrawableView(Context context) {
  super(context);
  paint.setColor(0x8a2be2);
  paint.setStyle(Style.STROKE);
  paint.setStrokeWidth(4);
  paint.setAntiAlias(true);
};


protected void onDraw(Canvas canvas) {
  int width = getWidth();
  int height = getHeight();
  int centerx = width/2;
  int centery = height/2;
  // Rotate the canvas with the azimut      
  if (azimut != null)
    canvas.rotate(-azimut*360/(2*3.14159f), centerx, centery);
  Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.rose4);
  canvas.drawBitmap(bmp,centerx- bmp.getWidth()/2,centery - bmp.getHeight()/2, paint);

  canvas.drawText("W", centerx-0, centery-55, paint);
  paint.setColor(0xffd02090);

  }
  }

  CustomDrawableView mCustomDrawableView;
  private SensorManager mSensorManager;
   Sensor accelerometer;
  Sensor magnetometer;

 protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);    // Register the sensor listeners
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
  accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

 }

  protected void onResume() {
  super.onResume();
 mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
 mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_UI);
  }

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

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

   float[] mGravity;
  float[] mGeomagnetic;
 public void onSensorChanged(SensorEvent event) {
  if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
   mGravity = event.values;
  if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
  mGeomagnetic = event.values;
 if (mGravity != null && mGeomagnetic != null) {
  float R[] = new float[9];
  float I[] = new float[9];
  boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
  if (success) {
    float orientation[] = new float[3];
    SensorManager.getOrientation(R, orientation);
    azimut = orientation[0]; // orientation contains: azimut, pitch and roll
   }
  }
 mCustomDrawableView.invalidate();
  }
  }

我需要添加textview。但我既不能添加xml,也不能在程序中使用textview。如何在指南针的上层添加textview?

4

0 回答 0