2011-07-05 91 views
0

我有一個android的問題,首先我想有一個按鈕,我每2秒移動到屏幕上的不同位置,但我不能這樣做(如果有人知道如何這將是非常有益的)。 Anywayz我的另一種方法是,使5個不同的按鍵在不同的位置,並與setVisibility()函數移動,但它崩潰中間我不知道爲什麼,這裏的代碼:在android中的屏幕上移動一個圖像按鈕

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(); 

如果有人能幫助我那很好,謝謝。

回答

1

你有沒有想過用動畫做這個?如果您的目標是蜂窩,則可以使用property animation;對於早期的平臺,您可以使用view animation

至於你的崩潰,你只能從UI線程修改UI元素,而不能從單獨的線程修改。您需要發回信號,或者使用其中一個(非常好)的幫助器來處理此問題,例如AsyncTask。

請參見:http://developer.android.com/resources/articles/painless-threading.html

+0

洛恩是正確的,崩潰是因爲你正試圖從後臺線程使用的UI元素。您可以使用處理程序或AsyncTask,也可以將所有內容都放在線程中,然後在主線程上執行。 – FoamyGuy

+0

@Lorne,我仍然是Android的初學者,我不知道如何使用動畫,如果有任何在線虛擬教程(尤其是視頻),會很棒 –

+0

在android中的動畫其實很簡單。 ..這個框架非常強大,爲你做了很多事情。 Honeycomb中基於屬性的動畫更加優雅和強大,但較早的Honeycomb方法並不困難。 有很多動畫教程在線...我發現這一個與谷歌,它似乎很初學者友好: http://www.barebonescoder.com/2010/06/android-development-more-animations-part- 1/ http://www.barebonescoder.com/2010/06/android-development-more-animations-part-2/ –

相關問題