0

I need to pass a value from my main Activity to a custom View.

In the main activity I have a SensorEventListener so I'm continuosly listening to the light sensor. In the onSensorChanged() method I read the value, and I need to send this value every time it changes to my custom View.

I don't know which is the best way to achive this.

UPDATE --

Method refered to SensorEventListener on main activity:

@Override
public void onSensorChanged(SensorEvent event) {
    float lumnes = event.values[0];
    GaugeView.setHandTarget(lumnes);
}

Method I have to send values to in custom view:

public void setHandTarget(float temperature) {
    if (temperature < minDegrees) {
        temperature = minDegrees;
    } else if (temperature > maxDegrees) {
        temperature = maxDegrees;
    }
    handTarget = temperature;
    handInitialized = true;
    invalidate();
}

I cannot use static references cause then I cannot call invalidate()

masmic
  • 3,526
  • 11
  • 52
  • 105
  • Are you trying to pass from one activity to another activity? or are you still in your Main Activity? Some code would be helpful. – William Riley Mar 05 '14 at 15:22
  • @William Riley They are 2 different classes. one is an activity, the other is a custom view that extends view – masmic Mar 05 '14 at 15:23
  • Im not sure if the answer below is clear enough. If not, please post your onSensorChange() method, and I will edit to be more specific. – William Riley Mar 05 '14 at 15:27
  • What exactly is the issue with your code? It should be setting the values, the way you have written it. Is there an error you can share? – William Riley Mar 05 '14 at 15:43
  • @William Riley well, it requests me to make setHandTarget() method static, but I can't do this ,because then i cannot call invalidate() method – masmic Mar 05 '14 at 15:44

2 Answers2

6

You could do this:

public CustomView extends View {
  ...
  private float[] values; //this 

  //setter
  public void setValues(float[] values) {
    this.values = values;
  }

}


public class MyActivity extends Activity implements SensorEventListener {

 private CustomView mCustomView;
 ...
    @Override
    public void onSensorChanged(SensorEvent event) {
        float[] values = event.values;
        mCustomView.setValues(values);    //pass the collected values to the view via setter
    }
}
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
0

Without seeing any of your code, the best advice I can give is to create a property in your view, and make it accessible from your Main Activity class. In your method that is checking the sensor, you can simply set the custom View's property that you created to be the value. Not so much passing the value as directly accessing it.

Assuming your value is a float, add something like this to your Custom view class:

public float sensorValue;

Access it from the sensor event listener like this:

CustomView.sensorValue = sensorValue;
William Riley
  • 878
  • 8
  • 13