SetonClicklistener在Android Studio中不起作用

发布于 2025-02-07 06:37:42 字数 630 浏览 1 评论 0原文

那是我的代码,非常简单和基本 公共按钮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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩动你心 2025-02-14 06:37:42

问题在于,

findViewById(R.id.txt1);
findViewById(R.id.btn1);

您是从.xml文件中获取视图,但是实际上您并未将值分配给任何对象...因此,当您尝试将方法调用到> btn1 < /code>是null(空)并引发错误,

因此只需分配您要获得的值的值,例如:

txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);

这将解决问题

The problem is here

findViewById(R.id.txt1);
findViewById(R.id.btn1);

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 the btn1 it's null (empty) and throws an error

So just assign the value you are getting to the views objects like so:

txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);

This will fix the problem

情栀口红 2025-02-14 06:37:42

将元素保存在变量中,并将OnClick方法设置为以下特定变量:

btn1 = findViewById(R.id.btn1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            txt1.setText("finalyyyyyyyyyyy");


        }
    });

Save the element in variable and set onClick method to that particular variable as below:

btn1 = findViewById(R.id.btn1);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            txt1.setText("finalyyyyyyyyyyy");


        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文