使用Glide加载图片时应用崩溃问题求助
解决Glide加载图片时"You must pass in a non null View"崩溃问题
嘿,这个问题其实很好定位——LogCat给出的**"You must pass in a non null View"**提示已经把原因说得明明白白:你调用Glide的into()方法时传入的home_ib1是null值,因为你只声明了这个ImageButton变量,却没有把它和XML布局里的对应控件绑定起来!
核心问题分析
看你的Java代码,你只做了变量声明:
ImageButton home_ib1;
但完全没调用findViewById()来完成控件的初始化,直接就传给Glide用了,这不崩溃才怪~
修复步骤
- 先初始化控件:在你的
onCreate()方法里(或者其他合适的生命周期方法中),先通过findViewById()把Java变量和XML控件关联起来,这一步必须放在Glide加载代码的前面。 - 确保布局文件正确绑定:别忘了在
onCreate()里先调用setContentView()加载你的布局文件,不然findViewById()也找不到控件。
修改后的完整Java代码片段
ImageButton home_ib1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_home_layout); // 替换成你实际的布局文件名 // 关键:先初始化ImageButton home_ib1 = findViewById(R.id.home_ib1); // 再执行Glide加载逻辑 Glide.with(Home.this) .load(R.drawable.moviep_24_hours_to_live) .override(98, 155) .centerCrop() .placeholder(R.drawable.moviep_24_hours_to_live) .into(home_ib1); }
额外布局优化提示
另外看你的XML布局,ScrollView里的RelativeLayout用了ConstraintLayout的约束属性(app:layout_constraintStart_toStartOf这类),这其实是无效的——RelativeLayout不支持ConstraintLayout的约束规则。如果想让这些约束生效,建议把RelativeLayout换成ConstraintLayout,修正后的XML如下:
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageButton android:id="@+id/home_ib1" android:layout_width="98dp" android:layout_height="155dp" android:layout_marginStart="16dp" android:layout_marginTop="155dp" android:background="@android:color/transparent" android:scaleType="fitCenter" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView>
当然,如果你坚持用RelativeLayout,就把那些app:layout_constraintXXX属性换成RelativeLayout的布局属性,比如android:layout_alignParentStart="true"、android:layout_marginTop="155dp"等。
内容的提问来源于stack exchange,提问作者Kiss Gyorgy
相关产品推荐
相关产品推荐

