SetonClicklistener在Android Studio中不起作用
那是我的代码,非常简单和基本 公共按钮btn1; public TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.txt1);
findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});
显示的错误是: 引起的是:java.lang.nullpointerexception:尝试调用虚拟方法'void android.widget.button.setonClickListener(android.view.view.view.view $ onclicklistener)'null对象参考
that is my code, very simple and basic
public Button btn1;
public TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.txt1);
findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});
and the error showing is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于,
您是从
.xml
文件中获取视图,但是实际上您并未将值分配给任何对象...因此,当您尝试将方法调用到> btn1 < /code>是null(空)并引发错误,
因此只需分配您要获得的值的值,例如:
这将解决问题
The problem is here
you are getting the views from the
.xml
file but you are not actually assigning the value to any object... so when you try to call a method to thebtn1
it's null (empty) and throws an errorSo just assign the value you are getting to the views objects like so:
This will fix the problem
将元素保存在变量中,并将OnClick方法设置为以下特定变量:
Save the element in variable and set onClick method to that particular variable as below: