============问题描述============
以下是我的摇一摇实现的代码
public class Yao extends Activity implements SensorEventListener { EditText tv =(EditText)findViewById(R.id.editText1); Button button =(Button)findViewById(R.id.button1); SensorManager sensorManager = null; Vibrator vibrator = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv.setText("初始文本"); } }); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //当传感器精度改变时回调该方法,Do nothing. } @Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); //values[0]:X轴,values[1]:Y轴,values[2]:Z轴 float[] values = event.values; if (sensorType == Sensor.TYPE_ACCELEROMETER) { if ((Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || Math .abs(values[2]) > 17)) { // Log.d("sensor x ", "============ values[0] = " + values[0]); // Log.d("sensor y ", "============ values[1] = " + values[1]); // Log.d("sensor z ", "============ values[2] = " + values[2]); tv.setText("摇一摇成功!!!"); //摇动手机后,再伴随震动提示~~ vibrator.vibrate(500); } } } }
为什么程序运行的时候会提示程序无响应然后就退出了?我看了一下网上的代码都是这么写的,问题出现在哪里呢?高分送上,请各位高手帮帮忙
============解决方案1============
控件初始化不能放在最上面
EditText tv =(EditText)findViewById(R.id.editText1); Button button =(Button)findViewById(R.id.button1);
这个需要在
setContentView(R.layout.activity_main);
后调用
============解决方案2============
看来LZ是新手啊,以后得认真学习
引用 1 楼 guoyoulei520 的回复:
控件初始化不能放在最上面
EditText tv =(EditText)findViewById(R.id.editText1); Button button =(Button)findViewById(R.id.button1);这个需要在
setContentView(R.layout.activity_main);
后调用
============解决方案3============
在UI线程中做了计算量大的操作了吧
时间: 2024-10-14 04:24:54