我正在尝试为Android编写一个非常简单的应用程序。 它应该做2件事:无法让按钮与其他代码同时工作
- Textips中的Dipslay方向传感器信息。
- 按钮单击显示烤面包。
随着下面的传感器信息的代码被显示,但不能点击按钮:
package com.example.hello;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroid extends Activity implements OnClickListener {
/* Called when the activity is first created. */
private SensorManager mSensorManager;
private Sensor mSensor;
private float[] mValues;
public void onClick(View v) {
// do something when the button is clicked
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "Hello", Toast.LENGTH_LONG);
toast.show();
}
private final SensorEventListener mListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
mValues = event.values;
setContentView(R.layout.main);
TextView t=(TextView)findViewById(R.id.status);
t.setText(Float.toString(mValues[0]) + "\n" +
Float.toString(mValues[1]) + "\n" +
Float.toString(mValues[2]));
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.start);
button.setOnClickListener(this);
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mSensorManager.registerListener(mListener, mSensor,
SensorManager.SENSOR_DELAY_GAME);
}
}
如果我评论的代码的一部分,其显示传感器信息的按钮开始工作:
private final SensorEventListener mListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
mValues = event.values;
/* setContentView(R.layout.main);
TextView t=(TextView)findViewById(R.id.status);
t.setText(Float.toString(mValues[0]) + "\n" +
Float.toString(mValues[1]) + "\n" +
Float.toString(mValues[2]));
*/ }
我在做什么错?如何让两件事同时工作?
为什么你在传感器事件监听器中再次设置内容视图?它已经设置在OnCreate() – Urban
谢谢大家!全部3个答案都是对的:) – defhlt