闪烁背景背景

2023-09-07 23:34:53 作者:春的气息

我有一个的LinearLayout 有几个按钮 TextViews 。我想我的背景,以一定的时间间隔闪烁。说从红色到白色到红色等。现在,我想这code。但它给了我一个空指针异常。

I have a LinearLayout with a few Buttons and TextViews. I want my background to flash at timed intervals. say from red to white to red and so on. right now, I am trying this code. but it gives me a null pointer exception.

    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

请帮我我要去哪里错了?

Please help me where am I going wrong?

推荐答案

您已经指定了错误的查看 ID这里 findViewById(R.layout。 activity_main)。它应该是这样的:

You have specified the wrong View id here findViewById(R.layout.activity_main). It should be something like:

findViewById(R.id.your_view_id);

此外,请务必打电话的setContentView(R.layout.activity_main)右后 super.onCreate

修改

下面是code,它可以让你只改变你想要的任何颜色的背景颜色。它看起来像AnimationDrawable.start()不工作,如果从 Activity.onCreate 调用,所以我们必须使用 Handler.postDelayed 点击这里

Here is the code that allows you to change only the background color with any colors you want. It looks like AnimationDrawable.start() doesn't work if called from Activity.onCreate, so we have to use Handler.postDelayed here.

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