我在使用Android Studio对图像进行动画时遇到了空对象引用错误。

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

i am getting a null object reference error in android studio while animating a image

问题

public class MainActivity extends AppCompatActivity {

    public void click(View view) {
        ImageView bart = (ImageView) findViewById(R.drawable.bart);
        bart.animate().alpha(0);
    }
}

这是错误信息:

Caused by: java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()'
英文:
public class MainActivity extends AppCompatActivity {

    public void click(View view) {
        ImageView bart = (ImageView) findViewById(R.drawable.bart);
        bart.animate().alpha(0);
    }
}

This is the error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewPropertyAnimator android.widget.ImageView.animate()' on a null object reference

答案1

得分: 1

似乎你在引用一个“drawable id”,而不是一个“view id”。
对于视图,请使用R.id,而对于可绘制资源,请使用R.drawable

英文:

It seems that you are referencing to a drawable id and not a view id.
Use R.id for views, R.drawable is for drawable resource.

答案2

得分: 1

从:

R.drawable.bart

变成:

R.id.bart

并且你确定在 onCreate() 方法中调用了 setContentView() 方法(用于填充布局)吗?

英文:

Change from:

R.drawable.bart

in to:

R.id.bart

And are you sure that in onCreate() you call setContentView() method (which inflates layout)?

huangapple
  • 本文由 发表于 2020年4月7日 07:46:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/61070663.html
匿名

发表评论

匿名网友

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

确定