闪烁的背景

问题描述 投票:6回答:2

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

请帮帮我哪里出错了?

android animation
2个回答
18
投票

你在这里指定了错误的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);

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);
© www.soinside.com 2019 - 2024. All rights reserved.