7

我有一个和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

请帮助我我哪里出错了?

4

2 回答 2

22

您在这里指定了错误的Viewid findViewById(R.layout.activity_main)。它应该是这样的:

findViewById(R.id.your_view_id);

另外,请务必在setContentView(R.layout.activity_main)之后立即致电super.onCreate

编辑

这是允许您仅使用所需颜色更改背景颜色的代码。如果从 调用它看起来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);
于 2013-03-11T04:53:12.793 回答
5

试试这个

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);
于 2013-03-11T04:57:13.533 回答