[英]Changing image source of an imageview in a different layout
I can't find a solution to this anywhere, I'm still quite new to programming so it might be a simple question. 我在任何地方都找不到解决方案,我对编程还是很陌生,所以这可能是一个简单的问题。
In my MainActivity
I take the position of a ViewPager
. 在我的
MainActivity
我占据了ViewPager
的位置。 According to this position I want to change the source of an ImageView
which is placed in a layout that will inflate in a service. 根据这个位置,我想更改
ImageView
的源,该源放置在将在服务中膨胀的布局中。 But with my code I keep getting a NullPointerException
. 但是随着我的代码,我不断得到
NullPointerException
。 Do I need to declare the ImageView
differently because it's in a different layout than the currently showed one? 我需要以不同于当前显示的布局的方式声明
ImageView
吗?
public void OnClick(View view) {
pagenumber = viewPager.getCurrentItem();
imageView = (ImageView) findViewById(R.id.filterview);
switch (pagenumber){
case 0: imageView.setImageResource(R.drawable.goghfilter);
break;
case 1: imageView.setImageResource(R.drawable.background3);
break;
Thanks for any help! 谢谢你的帮助!
Well remember that the class inflated with the layout will only find views in that layout, try to findById a view not in that layout will cause errors. 很好记住,使用布局夸大的类将仅在该布局中查找视图,请尝试为不在该布局中的视图findById查找会导致错误。 To resolve this, define a custom layout inflater, inflate the layout with the image , then used that view inflated and perform a findById on it.
要解决此问题,请定义一个自定义布局填充器,将图像填充到布局中,然后使用该视图填充后的视图并对其执行findById。
Try This: 尝试这个:
ImageView mImageView = (ImageView) MainActivity.this.getLayoutInflater().inflate(R.layout.layout,null).findViewById(R.id.imageView); mImageView.setImageResource(R.drawable.icon);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.