2013-03-11 116 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);