我有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
Run Code Online (Sandbox Code Playgroud)
请帮帮我哪里出错了?
Vla*_*nov 20
您View在此处指定了错误的ID findViewById(R.layout.activity_main).它应该是这样的:
findViewById(R.id.your_view_id);
Run Code Online (Sandbox Code Playgroud)
此外,请务必在setContentView(R.layout.activity_main)之后立即致电super.onCreate
编辑:
以下代码允许您仅使用所需的任何颜色更改背景颜色.AnimationDrawable.start()如果调用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);
Run Code Online (Sandbox Code Playgroud)
尝试这个
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);
Run Code Online (Sandbox Code Playgroud)
如果activity_main是您的 XML 文件名,则
setContentView(R.layout.activity_main);
Run Code Online (Sandbox Code Playgroud)
并在此处使用您的布局 ID
LinearLayout ll = (LinearLayout) findViewById(R.id.linear_layout_id);
Run Code Online (Sandbox Code Playgroud)