【问题标题】:I cannot set a onclick listener for image button我无法为图像按钮设置 onclick 侦听器
【发布时间】:2021-08-05 18:02:10
【问题描述】:
public class HomeActivity extends AppCompatActivity{
RecyclerView chillHits;
RecyclerView coolSongs;
HomeAdaptor homeAdaptor;
SongCollection songCollection = new SongCollection();

ImageButton imageButton;
ImageButton imageButton2;
ImageButton imageButton3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    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();
        }
    });

    setContentView(R.layout.activity_home);

    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);
}



}

错误:原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)”

【问题讨论】:

    标签: java android-studio


    【解决方案1】:

    1)你在super.onCreate之后忘记了setContentView(R.layout.YOURLAYOUT)

    2)确保您的 XML 文件具有相同的 ImageView ID

    【讨论】:

    • 我已经添加了 setContentView 并且 XML 文件是相同的 id
    • 注释掉 on click 监听器的 7 行代码使应用程序运行得非常好。但我确实需要 ImageButtons 的点击次数
    • @Alpha1229 ,将 setContentView 放在 super.onCreate 之后
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多