英文:
Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference
问题
我正在尝试制作一个简单的动画,其中的图像最初不会显示,但在出现后会从屏幕左侧旋转180度,持续一段时间。因此,我在onCreate方法中编写了以下脚本:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView Bart = (ImageView) findViewById(R.id.bart);
Bart.animate().translationXBy(-3000);
Bart.animate().translationXBy(4000).rotation(180).setDuration(2000);
}
但由于某种原因,我收到一个错误,指示我正在尝试在空对象引用上调用虚拟方法。可能是什么问题?谢谢
英文:
I'm trying to make a simple animation with a image that iniatially it doesn't appear but after it appears rotating 180 degrees for certain a amount of seconds from the left of the screen.
So i made a script inside the onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView Bart = (ImageView) findViewById(R.id.bart);
Bart.animate().translationXBy(-3000);
Bart.animate().translationXBy(4000).rotation(180).setDuration(2000);
}
But for some reason i'm getting an error saying that i'm trying to invoke a virtual method on a null object reference.What could be the issue?Thanks
答案1
得分: 1
你在onCreate
中没有调用setContentView()
方法。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 将此行添加,使用你的布局 Id
ImageView bartImageView = (ImageView) findViewById(R.id.bart);
bartImageView.animate().translationXBy(-3000);
bartImageView.animate().translationXBy(4000).rotation(180).setDuration(2000);
}
另外,我有一些建议,变量名采用小写开头的驼峰命名法。为变量添加一些标识符,以表示它是什么,比如bartImageView
或bartIV
等。
英文:
You did not set setContentView()
in onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)// add this with your layout Id
ImageView bartImageView = (ImageView) findViewById(R.id.bart);
bartImageView.animate().translationXBy(-3000);
bartImageView.animate().translationXBy(4000).rotation(180).setDuration(2000);
}
Also few suggestions take variables with camelCase starting with small letter . Add some identifier to the variable which indicates what it is, like bartImageView
or bartIV
etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论