android setOnClickListener给空指针异常? [英] android setOnClickListener gives null pointer exception?

查看:75
本文介绍了android setOnClickListener给空指针异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为另一个视图的自定义对话框的 onClick 方法编写了代码。它给了我 nullpointer异常。我也尝试过使用布局充气机。它在 ok.setOnclickListener 上给我错误。我的代码有什么问题?

I have written code for onClick method for Custom Dialog top of the another view. It gives me nullpointer exception. I've also tried using Layout inflater. It gives me error on ok.setOnclickListener. What's wrong in my code?

 ImageButton search =(ImageButton) findViewById(R.id.search);
            search.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    Dialog searchDialog = new Dialog(Page.this);

                    /*LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


                     View layout = inflater.inflate(R.layout.search, null);
                     searchDialog.addContentView(layout, new LayoutParams(
                                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                     searchDialog.setContentView(layout);*/

                    searchDialog.setContentView(R.layout.search);
                    searchDialog.setTitle("Search Dialog");
                    searchDialog.setCancelable(true);

                    Button ok = (Button)findViewById(R.id.OkButton);
                    ok.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            String searchString = null;
                            EditText searchText = (EditText)findViewById(R.id.searchText);
                            if(searchText.getText()!=null){
                                searchString = searchText.getText().toString();
                            }
                            Log.i("TAG","Search word :"+searchString);

                        }
                    });

                    searchDialog.show();



                }


            });


推荐答案

您正在寻找创建活动的按钮对话框而不是对话框本身。 findViewById行应为:

You are looking for the button in the activity that creates the dialog instead of the dialog itself. The findViewById line should be:

Button ok = (Button)searchDialog.findViewById(R.id.OkButton);

这篇关于android setOnClickListener给空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆