2013-03-11 181 views
6

我有一個LinearLayout幾個ButtonsTextViews。我希望我的背景能夠定時閃爍,例如從紅色變成白色變成紅色,等等。現在,我正在嘗試這個代碼,但它給了我一個空指針異常。閃爍背景

LinearLayout ll = (LinearLayout) findViewById(R.layout.activity_main); 
Animation anim = new AlphaAnimation(0.0f, 1.0f); 
anim.setDuration(50); 
anim.setStartOffset(20); 
anim.setRepeatMode(Animation.REVERSE); 
anim.setRepeatCount(Animation.INFINITE); 
ll.startAnimation(anim); // shows null pointer exception at this line 

請幫我我在哪裏錯了?

+0

請附上logcat的。 – 2013-03-11 04:52:43

回答

15

您在此處指定了錯誤的View id findViewById(R.layout.activity_main)。它應該是這樣的:

findViewById(R.id.your_view_id); 

此外,請確保調用setContentView(R.layout.activity_main)之後super.onCreate

編輯

下面是允許你改變只與任何背景顏色代碼你想要的顏色。它看起來像AnimationDrawable.start() doesn't work if called from Activity.onCreate,所以我們必須在這裏使用Handler.postDelayed

final LinearLayout layout = (LinearLayout) findViewById(R.id.layout); 
final AnimationDrawable drawable = new AnimationDrawable(); 
final Handler handler = new Handler(); 

drawable.addFrame(new ColorDrawable(Color.RED), 400); 
drawable.addFrame(new ColorDrawable(Color.GREEN), 400); 
drawable.setOneShot(false); 

layout.setBackgroundDrawable(drawable); 
handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     drawable.start(); 
    } 
}, 100); 
+0

謝謝:)現在作品...你能幫我把顏色設置爲動畫嗎?另外,是否有可能我的按鈕n textviews不閃爍,只是背景部分呢? – newbee 2013-03-11 04:59:48

+0

@newtoandroid,檢查我更新的答案 – 2013-03-11 05:06:47

+0

當我使用這個,它只是將背景顏色設置爲紅色。沒有動畫。另外,對於線性佈局類型,「layout.setBackground」未定義。蝕給出3 fixes-'setBackgroundColor()','setBackgroundDrawable()'和'setBackgroundResource()' – newbee 2013-03-11 05:23:13

4

試試這個

LinearLayout ll = (LinearLayout) findViewById(R.id.activity_main); 
Animation anim = new AlphaAnimation(0.0f, 1.0f); 
anim.setDuration(50); 
anim.setStartOffset(20); 
anim.setRepeatMode(Animation.REVERSE); 
anim.setRepeatCount(Animation.INFINITE); 
ll.startAnimation(anim); 

。如果activity_main是你的XML文件名,然後

setContentView(R.layout.activity_main); 

,並使用你的佈局ID這裏

LinearLayout ll = (LinearLayout) findViewById(R.id.linear_layout_id);