我正在嘗試爲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