Android开发ImageButton设置onClick监听器报空指针异常如何解决
问题原因
空指针异常的核心触发原因是**findViewById执行时机早于布局加载**:
Android 中
setContentView()方法负责将指定布局文件加载到Activity实例中,只有该方法执行完成后,findViewById()才能从已加载的布局树中检索到对应id的控件实例。你的代码中先执行了三个ImageButton的findViewById操作,此时布局还未加载,所有查找操作都会返回null,后续调用setOnClickListener时就触发了空指针异常。
修复方案
- 调整代码执行顺序,将
setContentView(R.layout.activity_home)移动到super.onCreate(savedInstanceState)之后、所有findViewById操作之前执行即可。
修正后的onCreate方法代码如下:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 第一步先加载布局 setContentView(R.layout.activity_home); // 布局加载完成后再查找控件 imageButton = findViewById(R.id.imageButton2); imageButton2 = findViewById(R.id.imageButton3); imageButton3 = findViewById(R.id.imageButton4); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), SearchActivity.class)); finish(); } }); LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); LinearLayoutManager horizontalLayoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); chillHits = findViewById(R.id.chillHits); homeAdaptor = new HomeAdaptor(SongCollection.arrayChillHits); chillHits.setAdapter(homeAdaptor); chillHits.setLayoutManager(horizontalLayoutManager); coolSongs = findViewById(R.id.coolSongs); homeAdaptor = new HomeAdaptor(SongCollection.arrayCoolSongs); coolSongs.setAdapter(homeAdaptor); coolSongs.setLayoutManager(horizontalLayoutManager2); }
如果调整顺序后仍报错,可额外排查两个常见问题:
- 确认
activity_home.xml布局文件中确实存在id为imageButton2、imageButton3、imageButton4的ImageButton控件,id拼写、大小写完全匹配,没有笔误 - 确认导包时没有错误引入系统
android.R类,需引入你应用自身包名下的R类
内容的提问来源于stack exchange,提问作者Alpha1229
相关产品推荐
相关产品推荐

