2015-09-05 202 views
4

我有我的應用程序一個簡單的按鈕。
我要做到以下幾點事情:
當應用程序運行,按鈕的顏色發生變化連續地(例如每3秒)沒有任何接觸或聚焦,趕上客戶的眼睛點擊它。
有沒有辦法做到這一點?改變Android的按鈕顏色不斷

+0

哦,是的,但你嘗試過什麼? –

+0

使用'Handler'或'runOnUi thread' – Rustam

回答

3

使用以下代碼:

Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 
    @Override 
    public void run() 
    { 
    int rnd = (int)(Math.random() * 4); 
    if(rnd==0) 
     btn.setBackgroundColor(Color.BLUE); 
    if(rnd==1) 
     btn.setBackgroundColor(Color.RED); 
    if(rnd==2) 
     btn.setBackgroundColor(Color.GREEN); 
    if(rnd==3) 
     btn.setBackgroundColor(Color.YELLOW); 

    btn.invalidate(); 
    handler.postDelayed(runnable, 3000); 
    } 
}; 
handler.postDelayed(runnable, 3000); 
+0

什麼是invalidate(); ?日食不認識它 –

+0

刪除它後嘗試。 –

+0

無效()是用於刷新視圖 –

0

對於重複的顏色 -

Button btn = (Button) findViewById(R.id.btn); 
Handler handler = new Handler(); 

final Runnable r = new Runnable() { 
public void run() { 
    int i = 0; 
    if (i == 0) { 
    btn.setBackgroundColor(Color.YELLOW); 
    i++; 
    } else if (i == 1) { 
    btn.setBackgroundColor(Color.RED); 
    i++; 
    } else if (i == 2) { 
    btn.setBackgroundColor(Color.BLUE); 
    i++; 
    } else if (i == 3) { 
    btn.setBackgroundColor(Color.GREEN); 
    i = 0; 
    } 
    handler.postDelayed(this, 3000); // Set time in milliseconds 
} 
}; 

handler.postDelayed(r, 3000); // Set time in milliseconds 

此代碼改變按鈕的顏色的順序每隔3秒 - 黃,紅,藍,綠。

隨機顏色 -

Button btn = (Button) findViewById(R.id.btn); 
Handler handler = new Handler(); 

final Runnable r = new Runnable() { 
public void run() { 
    int i = (int) Math.random() * 3; 
    if (i == 0) { 
    btn.setBackgroundColor(Color.YELLOW); 
    } else if (i == 1) { 
    btn.setBackgroundColor(Color.RED); 
    } else if (i == 2) { 
    btn.setBackgroundColor(Color.BLUE); 
    } else if (i == 3) { 
    btn.setBackgroundColor(Color.GREEN); 
    } 
    handler.postDelayed(this, 3000); // Set time in milliseconds 
} 
}; 

handler.postDelayed(r, 3000); // Set time in milliseconds 

如果你喜歡這個答案,請把它標記爲selected

+0

感謝,但顏色變爲藍色一次,然後它不更改爲其他顏色 –

+0

@PouyaHeydari刪除'無效()'請 – FadedCoder

+0

@PouyaHeydari試試我的新代碼,我更新了它。 – FadedCoder

0

在繪製的XML文件中聲明的動畫

<?xml version="1.0" encoding="utf-8"?> 
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
android:oneshot="true"> 
<item android:drawable="@drawable/frame1" android:duration="50" /> 
<item android:drawable="@drawable/frame2" android:duration="50" /> 
<item android:drawable="@drawable/frame3" android:duration="50" /> 
etc... 
</animation-list> 

,然後在代碼中你可以寫

imageView.setBackgroundResource(R.drawable.movie); 
AnimationDrawable anim = (AnimationDrawable) 
imageView.getBackground(); 
anim.start();