英文:
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)?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论