Blinking background

I have a LinearLayout with several Buttons and TextViews . I want my background to flash at intervals of time from red to white to red and so on. Right now, I'm trying to use 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 will I be wrong?

+6
source share
2 answers

You specified an invalid View id here findViewById(R.layout.activity_main) . It should be something like:

 findViewById(R.id.your_view_id); 

Also, be sure to call setContentView(R.layout.activity_main) immediately 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 should 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); 
+15
source

try it

 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); 
+4
source

All Articles