java代码:
- <?xml version="1.0" encoding="utf-8"?>
- <!-- 声明xml的版本以及编码格式 -->
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <!-- 添加一个垂直的线性布局 -->
- <wyf.ytl.MainView
- android:id="@+id/mainView"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- />
- <!-- 向线性布局中添加一个自定义的View -->
- </LinearLayout> 说明:该布局非常简单,只需将自定义的View添加到一个垂直的线性布局中即可。
- 开发主逻辑代码,即读取手机的姿态,然后改变小水泡的坐标。首先搭建Sample.java的代码框架,如下所示。
- Java代码:package eoe.demo;
- //声明所在包
- import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;
- //引入相关类
- import android.app.Activity;
- //引入相关类
- import android.hardware.SensorListener;
- //引入相关类
- import android.hardware.SensorManager;
- //引入相关类
- import android.os.Bundle;
- //引入相关类
- public class Sample extends Activity {
- MainView mv;
- //主View
- int k = 45;
- //灵敏度
- private SensorManagerSimulator mySensorManager;
- //SensorManager对象引用
- //private SensorManager mySensorManager;
- //SensorManager对象引用
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //设置当前的用户界面
- mv = (MainView) findViewById(R.id.mainView);
- //获取主View
- //mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
- //获得SensorManager
- //调试时用
- mySensorManager = SensorManagerSimulator.getSystemService(this, SENSOR_ SERVICE); mySensorManager.connectSimulator();
- }
- private SensorListener mySensorListener = new SensorListener(){
- //监听器
- @Override
- public void onAccuracyChanged(int sensor, int accuracy) {
- }
- //重写onAccuracyChanged方法
- @Override
- public void onSensorChanged(int sensor, float[] values) {
- //重写onSensorChanged方法
- //此处省略的是接收手机姿态的数据并进行处理的代码,将在之后进行介绍
- }
- public boolean isContain(int x, int y){
- //判断点是否在圆内
- int tempx = (int) (x + mv.small.getWidth()/2.0);
- //得到水泡tempx坐标
- int tempy = (int) (y + mv.small.getWidth()/2.0);
- //得到水泡tempy坐标
- int ox = (int) (mv.big_X + mv.big.getWidth()/2.0);
- //得到大圆的X坐标
- int oy = (int) (mv.big_X + mv.big.getWidth()/2.0);
- //得到大圆的Y坐标
- if(Math.sqrt((tempx-ox)*(tempx-ox)+(tempy-oy)*(tempy-oy)) 36 >(mv.big.getWidth()/2.0-mv.small.getWidth()/2.0)){
- return false;
- //不在圆内
- }
- else {
- return true;
- //在圆内
- }
- }
- };
- @Override
- protected void onResume() {
- //重写的onResume方法
- mySensorManager.registerListener(
- //注册监听
- mySensorListener,
- //监听器SensorListener对象
- SensorManager.SENSOR_ORIENTATION,
- //传感器的类型为姿态
- SensorManager.SENSOR_DELAY_UI //频度
- );
- super.onResume();
- }
- @Override
- protected void onPause() {
- //重写onPause方法
- mySensorManager.unregisterListener(mySensorListener);
- //取消注册监听器
- super.onPause();
- }
- }