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?
You have specified the wrong View id here findViewById(R.layout.activity_main). It should be something like:
findViewById(R.id.your_view_id);
Also, make sure to call setContentView(R.layout.activity_main) right after super.onCreate
EDIT:
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);
Try this
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);
and If activity_main is your XML file name then
setContentView(R.layout.activity_main);
and use your layout id here
LinearLayout ll = (LinearLayout) findViewById(R.id.linear_layout_id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With