简体   繁体   中英

Android, how to make a thread sleep?

Here's my code that, upon a click of the "menu" button, slides 'menubtm' in or out of view. Is there a way to make it pause for a few milliseconds at every loop, so that it would be viable, how the menubtm moves?

Thanks!

@Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
 if(keycode == KeyEvent.KEYCODE_MENU){

    if ( menuBtmVisable == true )
    {
        menuBtmVisable = false;
        int xnow = menuBtmTopLimit;
        while (xnow<menuBtmTopLimit+120)
        {   
        xnow+=1;
        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(480, 120, 0, xnow);
        menubtm.setLayoutParams(lp); 
        }
    }
    else
    {
        menuBtmVisable = true;
        int xnow = menuBtmTopLimit+120;
        while (xnow>menuBtmTopLimit)
        {
        xnow-=1;
        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(480, 120, 0, xnow);
        menubtm.setLayoutParams(lp); 
        }
    }

 }
 return super.onKeyDown(keycode,event); 
}

EDIT: Thanks to your advice, I did it with animations.

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:toYDelta="120"
android:duration="500"
 />

This animation has to make the menu slide 120 px down... it does so ok, but then springs back into the old place. Is there a way to make it stay in the new location?

EDIT2: got it!

android:fillEnabled="true"
android:fillAfter="true"

Instead of hacking it yourself, use Android Animations , which is designed exactly for this sort of thing. It will be much more stable and probably look much better in the end.

To answer the title: Thread.sleep will make a thread sleep.

That said, you probably don't want to do that here. If I'm understanding your snippet, onKeyDown is being called from the UI thread. You don't want to delay the UI thread either by sleeping or by doing processing that will take a while. Instead you should start an animation and return as fast as you can. See View Animation and Property Animation in the Android Dev Guide for two ways of doing animation. (Note that the latter requires 3.x or higher.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM