开发者

Moving an imagebutton in the screen in android

开发者 https://www.devze.com 2023-03-18 17:33 出处:网络
i have a problem in android, first i wanted to have a button which i move every 2 secs to a different place on the screen, but i couldn\'t do that (if anyone knows how that would be very helpful).

i have a problem in android, first i wanted to have a button which i move every 2 secs to a different place on the screen, but i couldn't do that (if anyone knows how that would be very helpful). Anywayz my other way was to make 5 different buttons in different locations and move with the setVisibility() function, but it crashes in the middle i dont know why, here's the code:

final ImageButton[] face = new ImageButton[5];

    face[0] = (ImageButton) findViewById(R.id.ImageButton1);
    face[1] = (ImageButton) findViewById(R.id.ImageButton2);
    face[2] = (ImageButton) findViewById(R.id.ImageButton3);
    face[3] = (ImageButton) findViewById(R.id.ImageButton4);
    face[4] = (ImageButton) findViewById(R.id.ImageButton5);

    for(int i=0;i<5;i++)
    {
        face[i].setVisibility(View.GONE);
    }



    Thread timer=new Thread() {
        public void run(){
            for(int i=0;true;i++)
            {
                if(i开发者_如何转开发==5)
                {
                    i=0;
                }
                Log.v("VISIBLE AT I = ",Integer.toString(i));
                face[i].setVisibility(View.VISIBLE);
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    Log.v("CATCH","CATCH");
                    e.printStackTrace();
                }
                //Log.v("SLEPT","SLEPT");
                face[i].setVisibility(View.INVISIBLE);  // IT CRASHES HERE
                Log.v("INVISIBLE AT I = ",Integer.toString(i));
            }
        }
    };

    timer.start();

If anyone can help me that would be great, thanks.


Have you thought of doing this with an animation? If you're targeting Honeycomb, you can use a property animation; for earlier platforms you can use a view animation.

As for your crashes, you can only modify UI elements from the UI thread, not from a separate thread. You'd need to signal back, or use one of the (very good) helpers to handle this, such as AsyncTask.

See: http://developer.android.com/resources/articles/painless-threading.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号