我有LinearLayout
个Buttons
和TextViews
。我希望我的背景以定时间隔闪烁,比如说从红色到白色再到红色等等。现在,我正在尝试这个代码,但它给了我一个空指针异常。
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
请帮帮我哪里出错了?
答案 0 :(得分:18)
您在View
指定了错误的findViewById(R.layout.activity_main)
ID。它应该是这样的:
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);
答案 1 :(得分: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);