ImageView NullPointer错误

时间:2015-05-06 02:09:57

标签: android android-studio imageview

我有这个错误: java.lang.NullPointerException:尝试调用虚方法' void android.widget.ImageView.setImageResource(int)'在空对象引用上

我已按照步骤将ImageView放入活动中。错误是如何发生以及如何解决的?注意到在hadis_layout中,我使用RecylerView。感谢

  1. 我的ImageView

    <ImageView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@+id/hadisView"
    android:layout_gravity="center_horizontal"
    android:layout_weight="0.36"
    android:contentDescription="Hadis"
    android:src="@drawable/hadith01arabic"/>
    
  2. 我的活动

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hadis_layout);
    
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
    
        ImageView imageView = (ImageView) findViewById(R.id.hadisView);
        imageView.setImageResource(R.drawable.hadith01arabic);
    
    }
    

1 个答案:

答案 0 :(得分:1)

  • 您不能只是从中更改recycleview图像资源 activity。要做到这一点,你必须改变你的覆盖 onBindViewHolder类的RecycleViewAdapter函数。添加

    ViewHolderObject.imgResourceIdName.setImageResource(R.drawable.image_name);

    onBindViewHolder类中的RecycleViewAdapter函数,其相关ID为itemView 改变了。 (此处imgResourceIdName位于recycleView single_rv_item.xml 资源文件中。)

当您尝试将图像资源设置为不在ImageView文件中的resouce_layout.xml时,会出现上述错误。这意味着即使您按照

设置图像资源

imageView.setImageResource(R.drawable.hadith01arabic);
  imageView的对象是 null

ImageView imageView = (ImageView)findViewById(R.id.hadisView);

您刚刚初始化 null imageView对象变量 ImageView 数据类型。因为findViewById(R.id.hadisView)没有指向任何资源。检查hadisView名为 imageView 的资源是否首先显示在相关的 resource.xml 文件中。