Pass value from Activity to custom View

青春壹個敷衍的年華 提交于 2019-12-11 18:15:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!