问题
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()
回答1:
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
}
}
回答2:
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;
来源:https://stackoverflow.com/questions/22201761/pass-value-from-activity-to-custom-view