我有一个带有几个按钮和TextView的LinearLayout.我希望我的背景以定时间隔闪烁,比如说从红色到白色再到红色等等.现在,我正在尝试这个代码,但它给了我一个空指针异常.
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
请帮帮我哪里出错了?
解决方法
您在此处指定了错误的View ID findViewById(R.layout.activity_main).它应该是这样的:
findViewById(R.id.your_view_id);
此外,请确保在super.onCreate之后立即调用setContentView(R.layout.activity_main)
编辑:
以下代码允许您仅使用所需的任何颜色更改背景颜色.它看起来像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);