闪烁背景

8

我有一个带有几个按钮和文本视图的LinearLayout。 我想让我的背景在定时间隔内闪烁,例如从红色到白色再到红色等。 目前,我正在尝试使用此代码,但它会导致空指针异常。

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

请帮我找出错误在哪里?

请附上logcat日志。 - Dinesh Prajapati
2个回答

24

你在这里指定了错误的View id:findViewById(R.layout.activity_main)。它应该是类似于:

findViewById(R.id.your_view_id);

此外,请务必在super.onCreate之后立即调用setContentView(R.layout.activity_main)

编辑:

以下的代码可以让您仅使用任何颜色更改背景颜色。 似乎AnimationDrawable.start()如果从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);

谢谢 :) 现在可以了...你能帮我设置动画的颜色吗?另外,我的按钮和文本视图不闪烁,只有背景部分闪烁,这可能吗? - newbee
当我使用它时,它只是将背景颜色设置为红色。没有动画。而且,对于线性布局类型,'layout.setBackground'未定义。Eclipse 提供了三个修复方案- 'setBackgroundColor()'、'setBackgroundDrawable()' 和 'setBackgroundResource()'。 - newbee
哎呀,应该是 setBackgroundDrawable。如果您没有任何动画,请确保调用 drawable.start()。请注意,在调用 setBackgroundDrawable 之后必须调用它。 - Vladimir Mironov
我调用了drawable.start()但仍然只显示红色背景屏幕。 - newbee
setBackgroundDrawable()已被弃用,请使用ViewCompat.setBackground(layout,drawable);代替。 - Sam

6

试试这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接