Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference

huangapple go评论70阅读模式
英文:

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);
}

另外,我有一些建议,变量名采用小写开头的驼峰命名法。为变量添加一些标识符,以表示它是什么,比如bartImageViewbartIV等。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月16日 21:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63921052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定