将值从活动传递到自定义视图 [英] Pass value from Activity to custom View

查看:20
本文介绍了将值从活动传递到自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个值从我的主 Activity 传递到自定义视图.

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

在主要活动中,我有一个 SensorEventListener,所以我一直在监听光传感器.在 onSensorChanged() 方法中,我读取了该值,每次更改到我的自定义视图时,我都需要发送此值.

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.

更新 --

在主要活动中引用 SensorEventListener 的方法:

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();
}

我不能使用静态引用,因为我不能调用 invalidate()

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

推荐答案

你可以这样做:

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
    }
}

这篇关于将值从活动传递到自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆