我是Android的新手...我开发了一个应用程序,通过单击按钮来转换图像,我添加了一个Handler Runnable以自动转换图像(当没有按下按钮时),延迟时间为5000毫秒。但是我必须在按下按钮的时候停止Handler这个延迟,因为某些原因我不能这样做。
public class MainActivity extends AppCompatActivity {
private Integer images[]={R.drawable.pic1, R.drawable.pic21, ....
public int currImage=0;
public int ThreadCnt = 0;
public boolean backInt=true,forwardInc=false, ThreadInc=true;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initializeImageSwitcher();
setInitialImage();
setImageRotateListener();
final Handler handler = new Handler();
final Runnable run = new Runnable() {
@Override
public void run() {
//forwardInc is a Boolean indicating that click button occurred
if(forwardInc){
//and in this case (of forwardInc=true) I want to stop runnable for 5sec
handler.removeCallbacks(this);
handler.postDelayed(this, 5000);
forwardInc=false;
setInitialImage();
setImageRotateListener();
currImage++;
ThreadCnt++;
}
handler.postDelayed(this, 5000);
}
};
handler.post(run);
这是按钮点击的代码
public void setImageRotateListener() {
final Button rotatebutton=(Button) findViewById(R.id.btnRotateImage);
rotatebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
currImage++;
//forwardInc indicating that click button occurred
forwardInc=true;
...
setCurrentImage();
...
答案 0 :(得分:0)
目前还不清楚你要做什么。但据我所知,请尝试以下方法:
首先,在班级中设置Runnable
和Handler
全局。
public class MainActivity extends AppCompatActivity{
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
public void run(){/**/}
}
//other declarations.
//methods
}
runnable的内部运行方法:
public void run(){
setInitialImage(); //probably set next image
currImage++;
ThreadCnt++;
handler.postDelayed( this, 5000 )
}
现在在onClick中:
public void onClick(View view){
handler.removeCallbacks(this);
handler.postDelayed(this, 5000);
//no idea why you are using other code here.
}
在onCreate里面:
//other lines
setImageRotateListener();
handler.post(runnable);