有2个类(class); MainActivity
和 SimpleFLashLighImpl
。
在 MainActivity
类中,我输入了一段代码以从编辑框“no”中获取字符串
然后将其转换为整数“intdelay”。
这是代码的 MainActivity 部分:
public static volatile int intdelay = 1000;
textView=(TextView)findViewById(R.id.textView);
delay=(EditText)findViewById(R.id.edttxt);
String no=delay.getText().toString(); //this will get a string
try{
MainActivity.intdelay = Integer.parseInt(no);
}catch(NumberFormatException ex){ // handle your exception
}
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textView.setText(delay.getText());
}
});
在另一个类中,我试图访问“intdelay”int 值以使用处理程序进行延迟。 这是代码的其他类部分:
public void switchFlash() {
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (isFlashOn()) {
turnOffFlash();
x++;
} else if (x>10) {
turnOffFlash();
}
else
{
turnOnFlash();
}
handler.postDelayed(this, MainActivity.intdelay);
}
};
handler.postDelayed(runnable,MainActivity.intdelay);
}
但问题是每次我得到在 MainActivity
类开始时初始化的 1000 延迟。
解决方案是什么?
最佳答案
永远不要改变 intdelay 的值。 MainActivity.intdelay = Integer.parseInt(no);
比较,而不是改变。使用 ==
设置新值。
您还应该将变量声明为私有(private)并构建 getter/setter 方法。
如果别处不需要,您还应该考虑将延迟变量移动到您的 Runnable 中。
关于java - 访问来自不同类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063486/