【发布时间】:2016-08-21 11:04:30
【问题描述】:
有 2 个类; MainActivity 和 SimpleFLashLighImpl。
在MainActivity 类中,我放置了一个代码以从编辑框中获取字符串“否”
然后将其转换为整数'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的语句,所以它始终保持在初始值1000。也许int intdelay = Integer.parseInt(no)语句是为了改变它,但是它引入了一个块本地变量,而不是保持类变量不变。但是,即使您删除类型声明,它也可能不会执行您想要的操作,因为该操作似乎发生在按钮的onClick方法中,您再次没有触及类变量。