Reputation: 1784
I'm trying to write a very simple app for Android. It should do 2 things:
With code below sensor information is displayed but button can't be clicked:
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);
}
}
If I comment part of code which display sensor information the button starts to work:
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]));
*/ }
What am I doing wrong? How to get both things working at the same time?
Upvotes: 2
Views: 123
Reputation: 5168
Maybe you could try and set the context view on onCreate only. Don't set it again on the SensorEvent listener.
Upvotes: 4
Reputation: 24181
just delete the line setContentView(R.layout.main)
from your method onSensorChanged
, it is duplicated because there is already the method setContentView()
on your onCreate()
method ,
let me know if there is a problem
Upvotes: 3